Question:
Find the prefix that can match strings
For this question, you only need to keep asking for next until next is 0. Remember that the answer is the total length minus the next length.
1 #include <iostream> 2 #include <cstdio> 3 #include<string> 4 using namespace std; 5 6 #define N 1000100 7 int a[N],b[N],next[N]; 8 int m; 9 void getNext(){10 next[0]=0;11 next[1]=0;12 for(int i=1;i<m;i++){13 int j=next[i];14 while(b[j]!=b[i]&&j) j=next[j];15 if(b[j]==b[i]) next[i+1]=j+1;16 else next[i+1]=0;17 }18 }19 20 int main()21 {22 int T,count;23 cin>>T;24 string s;25 for(int i=1;i<=T;i++){26 cin>>s;27 m=s.length(),count=0;28 int t=m;29 for(int k=0;k<m;k++) b[k]=s.at(k);30 getNext();31 //a[count++]=m;32 33 while(next[m])34 {35 a[count++]=t-next[m];36 m=next[m];37 }38 cout<<"Case #"<<i<<": "<<count+1<<endl;39 for(int i=0;i<count;i++) cout<<a[i]<<‘ ‘;40 cout<<t<<endl;41 }42 return 0;43 }