power strings

题目大意:

             求每个字符串的最短循环子串,输出循环次数。

             到'.'时停止。

发现KMP算法中的next数组恰好满足这个性质,如果n%(n-next[n])==0,则为好几个的循环,输出

n/(n-next[n]),否则放心输出1。

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 using namespace std;
 5 const int maxn=1e6+7;
 6 char a[maxn];
 7 int n;
 8 int P[maxn];
 9 void process(){
10     int j=0;
11     for(int i=1;i<=n;i++){
12         while(j>0&&a[j+1]!=a[i+1]) j=P[j];
13         if(a[j+1]==a[i+1]) j++;
14         P[i+1]=j;
15     }
16 }
17 int main(){
18     for( ; ; ){
19         scanf("%s",a+1);
20         if(a[1]=='.') break;
21         n=strlen(a+1);
22         process();
23         if(n%(n-P[n])==0){
24             cout<<n/(n-P[n])<<endl; 
25         } 
26         else cout<<1<<endl;
27     } 
28     return 0;
29 } 

在洛谷上用next会说ambiguous

所以换个.......

原文地址:https://www.cnblogs.com/lcan/p/9414559.html