1. 程式人生 > >POJ1961(kmp中Next數組的性質)

POJ1961(kmp中Next數組的性質)

test case poj next calc kmp ase 數組 ++ return

對於某個位置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 }

POJ1961(kmp中Next數組的性質)