POJ1961(kmp中Next数组的性质)

对于某个位置i,i - Next[i]是循环节长度,i整除(i - Next[i])时是完整的几个循环元。

 

 1 const int maxn = 1e6 + 5;
 2 int n, kase, Next[maxn];
 3 char ch[maxn];
 4 
 5 inline void Calc_Next(char *a, int len) {
 6     Next[1] = 0;
 7     for (int i = 2, j = 0; i <= len; ++i) {
 8         while (j > 0 && a[i] != a[j + 1])    j = Next[j];
 9         if (a[i] == a[j + 1])    j++;
10         Next[i] = j;
11     }
12 }
13 
14 int main() {
15     while (~scanf("%d", &n) && n) {
16         scanf("%s", ch + 1);
17         Calc_Next(ch, n);
18         printf("Test case #%d\n", ++kase);
19         for (int i = 2; i <= n; ++i) {
20             if (i % (i - Next[i]) == 0 && i / (i - Next[i]) > 1) {
21                 printf("%d %d\n", i, i / (i - Next[i]));
22             }
23         }
24         puts("");
25     }
26     return 0;
27 }

 

posted @ 2019-03-22 09:18  AlphaWA  阅读(149)  评论(1编辑  收藏  举报