Title Description
A string is perfect if it has the smallest lexicographical ordering among its cyclic rotations.
For example: "0101" is perfect as it is the smallest string among ("0101", "1010", "0101", "1010").
Given a 01 string, you need to split it into the least parts and all parts are perfect.
Input description
The first line of the input gives the number of test cases, T (T≤300). T
test cases follow.
For each test case, the only line contains one non-empty 01 string. The length of string is not exceed 200.
Output description
For each test case, output one string separated by a space.
Sample input
4
0
0001
0010
111011110
Example output
0
0001
001 0
111 01111 0
Main idea of the title:
A string is called a perfect string if it has the smallest dictionary order in its circular rotation. Given a 01 string, it is required to divide it into a minimum number of substrings, so that each substring is a perfect substring.
Analysis:
To divide it into the fewest substrings, let each substring be as long as possible. You can look for the end of the current substring from the back, and then use the next end of the current endpoint as the starting point of the next substring to continue looking. Because of the small amount of data in this question, when deciding whether it is a perfect substring, we can directly find the smallest lexicographic ordering string in the range of judgment. Compared with the current string, the same substring is perfect.
See the code for detailed explanation.
#include <iostream> #include <cstring> #include <algorithm> #include <string> #include <vector> #define ll long long #define INF 0x3f3f3f3f using namespace std; char str[205]; int f(int index,int eindex){ int n=eindex-index+1; char tmp[405]; for(int i=1;i<=n;i++){ tmp[i]=tmp[i+n]=str[index+i-1]; } int i=1,j=2,k; while(i<=n&&j<=n){ for(k=0;k<n&&tmp[i+k]==tmp[j+k];k++); if(k==n) break; if(tmp[i+k]>tmp[j+k]){ i=i+k+1; if(i==j) i++; } else{ j=j+k+1; if(i==j) j++; } } int ans=min(i,j);//Get the starting point of the smallest lexicographic string in the original string. //Comparing whether the original string is equal to the minimum lexicographic ordinal string int flag=0; for(int l=ans;l<=ans+n-1;l++){ if(tmp[l]!=tmp[l-ans+1]){ flag=1; } } if(flag){ return false; } else{ return true; } } int main(){ int t; scanf("%d",&t); while(t--){ vector<int> v; scanf("%s",str+1); int n=strlen(str+1); int i=1,j; while(i<=n){ j=n; for(;j>=i;j--){ if(f(i,j)){ v.push_back(j); break; } } i=j+1; } int pre=1; for(int i=0;i<v.size();i++){ for(int j=pre;j<=v[i];j++){ cout<<str[j]; } cout<<" "; pre=v[i]+1; } cout<<endl; } return 0; }