hdu 1358 KMP的next数据运用

由于next[i]保存的是前i-1个字符中最大的重复子序列,那么i-next[i]就是循环节。

#include<cstdio>
#include<cstring>
#include<iostream>
using namespace std;
int next[1000100];
void getnext(char *str)
{
    int j,k;
    memset(next,0,sizeof(next));
    j=0;
    k=-1;
    next[0]=-1;
    while(str[j])
    {
        if(k==-1 || str[j]==str[k])
            next[++j]=++k;
        else
            k=next[k];
    }
}
int main()
{
    int n,i,j;
    int Case=0;
    char str[1000010];
    while(scanf("%d",&n),n)
    {
        scanf("%s",&str);
        getnext(str);
        printf("Test case #%d\n",++Case);
        for(i=2;i<=n;i++)
        {
            int x=i/(i-next[i]);
            if(i%(i-next[i])==0&&x>1)
                printf("%d %d\n",i,x);
        }
        printf("\n");
    }
    return 0;
}

 

posted @ 2013-07-05 17:39  fangguo  阅读(108)  评论(0编辑  收藏  举报