POJ-2752 Seek the Name, Seek the Fame

//题目考的是对KMP失配指针的理解,当最后一位失配(即'\0'那里)时,指针会移动到前缀对应匹配的部分,所以这个长度是我们要的,然后接着这个新的前缀的失配指针移到的部分,与这个前缀的后缀也是匹配的..这样一直滚下去就可以了得到所有可能的值.

AC代码:

#include<stdio.h>
#include<string.h>
#define max 400005
char t[max];
int next[max];
int a[max];
int len;
void get_next()
{
    int i=0;
    int j=-1;
    next[0]=-1;
    while(i<len)
    {
        if(j==-1||t[i]==t[j])
        {
            i++;
            j++;
            next[i]=j;
        }
        else
        {
            j=next[j];
        }
    }
}
int main()
{
    while(scanf("%s",t)!=EOF)
    {
        len=strlen(t);
        memset(next,0,sizeof(next));
        get_next();
        int i,j;
        int cnt=0;
        j=next[len];
        while(j>0)
        {
            a[cnt++]=j;
            j=next[j];
        }
        for(i=cnt-1;i>=0;i--)
        {
           printf("%d ",a[i]);
        }
        printf("%d\n",len);
    }
    return 0;
}

你可能感兴趣的:(POJ-2752 Seek the Name, Seek the Fame)