首页 > 代码库 > POJ 1961 Period (KMP)

POJ 1961 Period (KMP)

解题思路:

 利用next 数组的性质求解重复子串。循环节的长度为i - next[i];

#include <iostream>
#include <cstring>
#include <cstdlib>
#include <vector>
#include <cmath>
#include <algorithm>
#include <cstdio>
using namespace std;
const int maxn = 1000000 + 10;
char s[maxn];
int n;
int next[maxn];
int main()
{
    int kcase = 1;
    while(scanf("%d", &n)!=EOF)
    {
        if(n == 0) break;
        scanf("%s", s);
        next[0] = 0; next[1] = 0;
        for(int i=1;i<n;i++)
        {
            int j = next[i];
            while(j && s[i] != s[j]) j = next[j];
            next[i+1] = (s[i] == s[j]) ? j + 1 : 0;
        }
        printf("Test case #%d\n", kcase++);
        for(int i=2;i<=n;i++)
        {
            if(next[i] > 0 && i % (i - next[i]) == 0)
            {
                printf("%d %d\n", i, i / (i - next[i]));
            }
        }
        printf("\n");
    }
    return 0;
}

POJ 1961 Period (KMP)