POJ 1961 KMP

链接:

http://poj.org/problem?id=1961

题意:

给你一个字符串,求这个字符串到第i个字符为止的循环节的次数。

比如aabaabaabaab,长度为12.到第二个a时,a出现2次,输出2.到第二个b时,aab出现了2次,输出2.

到第三个b时,aab出现3次,输出3.到第四个b时,aab出现4次,输出4.

题解:

在2406的外面套一层循环就可以了

代码:

31 char s[MAXN];
32 int Next[MAXN];
33 
34 void buildNext(char P[]) {
35     int m = strlen(P);
36     int i = 0, j;
37     j = Next[0] = -1;
38     while (i < m) {
39         while (-1 != j && P[i] != P[j]) j = Next[j];
40         Next[++i] = ++j;
41     }
42 }
43 
44 int main() {
45     int n;
46     int cas = 1;
47     while (cin >> n, n) {    
48         scanf("%s", s);
49         memset(Next, 0, sizeof(Next));
50         cout << "Test case #" << cas++ << endl;
51         buildNext(s);
52         rep(i, 2, n + 1)  if (Next[i] > 0 && i % (i - Next[i]) == 0)
53             cout << i << ' ' << i / (i - Next[i]) << endl;
54         cout << endl;
55     }
56     return 0;
57 }
原文地址:https://www.cnblogs.com/baocong/p/6790076.html