标签:
KMP算法
Next[]函数深入理解,Next[]当前字符前匹配字符数,串长n-Next[i]=串内循环子串的长度p。
本题求子循环串内循环节数。
1 #include<iostream> 2 #include<stdio.h> 3 using namespace std; 4 5 char s[1000001]; 6 int Next[1000001]; 7 8 void getNext(int n){ 9 int i=0,j=-1; 10 Next[0]=-1; 11 while(i<n){ 12 if(j==-1||s[i]==s[j]){ 13 i++;j++; 14 Next[i]=j; 15 } 16 else j=Next[j]; 17 } 18 } 19 20 int main() 21 { 22 int n,k,t=1,p; 23 //freopen("pe.txt","r",stdin); 24 while(cin>>n&&n>1&&n<1000001){ 25 cin>>s; 26 getNext(n); 27 cout<<"Test case #"<<t++<<endl; 28 for(k=2;k<=n;k++){ 29 p=k-Next[k]; //循环节的长度 30 if(k%p==0&&k/p>1) 31 cout<<k<<‘ ‘<<k/p<<endl; //若字符串由循环节构成,第k个字母前完整循环节数 32 } 33 cout<<endl; 34 } 35 return 0; 36 }
标签:
原文地址:http://www.cnblogs.com/Locked-J/p/4293043.html