poj1961 Period

题目链接:http://poj.org/problem?id=1961

题意就是求一个串的连续重复子串

是KMP中next数组的应用

答案即为如果j%(j-f[j])==0那么最长重复次数为j/(j-f[j])(j表示字符串的当前位置)

自己可以证明,也可以记住这个结论

代码:

 1 #include<iostream>
 2 #include<cstring>
 3 #include<stdlib.h>
 4 #include<stdio.h>
 5 using namespace std;
 6 int n;
 7 char s[1001000];
 8 int f[1001000];
 9 void callfail()
10 {
11    int i,j=0,k=-1;
12    f[0]=-1;
13    while(j<n)
14    {
15         if(k==-1||s[k]==s[j])
16         {
17            k++;j++;
18            if(j%(j-k)==0 && j/(j-k)>1)
19                    cout<<j<<" "<<j/(j-k)<<endl;
20            f[j]=k;
21         }
22         else k=f[k];
23    }
24 }
25 int main()
26 {
27     int iCase=1;
28    while(scanf("%d",&n)!=EOF && n) 
29    {
30       cin>>s;
31       cout<<"Test case #"<<iCase++<<endl;
32       callfail();
33       cout<<endl;
34 
35    }
36    return 0;
37 }
原文地址:https://www.cnblogs.com/xiaozhuyang/p/poj961.html