hdu 1358 Period (KMP求循环次数)

Problem - 1358

  KMP求循环节次数。题意是,给出一个长度为n的字符串,要求求出循环节数大于1的所有前缀。可以直接用KMP的方法判断是否有完整的k个循环节,同时计算出当前前缀的循环节的个数。

代码如下:

 1 #include <cstdio>
 2 #include <cstring>
 3 #include <iostream>
 4 #include <algorithm>
 5 
 6 using namespace std;
 7 
 8 const int N = 1111111;
 9 char buf[N];
10 int next[N];
11 
12 void getNext(char *str, int len) {
13     int i = 0, j = -1;
14     next[0] = -1;
15     while (i <= len) {
16         while (j > -1 && str[i] != str[j]) j = next[j];
17         i++, j++;
18         next[i] = j;
19     }
20 }
21 
22 typedef pair<int, int> PII;
23 PII rec[N];
24 
25 int main() {
26     int n, cas = 1;
27     while (cin >> n && n) {
28         cin >> buf;
29         getNext(buf, n);
30 //        for (int i = 0; i <= n; i++) cout << next[i] << ' '; cout << endl;
31         int cnt = 0;
32         for (int i = 1; i <= n; i++) {
33             if (i % (i - next[i])) continue;
34             if (i / (i - next[i]) == 1) continue;
35             rec[cnt++] = PII(i, i / (i - next[i]));
36         }
37         sort(rec, rec + cnt);
38         printf("Test case #%d
", cas++);
39         for (int i = 0; i < cnt; i++) {
40             printf("%d %d
", rec[i].first, rec[i].second);
41         }
42         puts("");
43     }
44     return 0;
45 }
View Code

——written by Lyon

原文地址:https://www.cnblogs.com/LyonLys/p/hdu_1358_Lyon.html