POJ 2752 Seek the Name, Seek the Fame (KMP next数组再次应用)

题意:常规猜题意,这道题问的是字符串S,有多少个S的前缀是S的后缀

思路:sb了,next想的太浅,看了眼题解,因为我们next数组求的是字符串前缀的最长后缀,我们都有最长的匹配长度了,其他的都是这个最长匹配长度的子串,那我们其实找的就是最长匹配前缀的最长匹配前缀(你懂的)

代码:(在手撕next的时候又又又又忘了,老年人记忆力)

#include <cstdio>
#include <cstring>

const int maxn=1e6+7;
char a[maxn];
int next[maxn];
int len;
void getnext()
{
    int j=0,k=-1;
    next[0]=-1;
    while(j<len){
        if(k==-1||a[j]==a[k])next[++j]=++k;
        else k=next[k];
    }
}
int stk[maxn],top;
int main()
{
    while(~scanf("%s",a)){
        len=strlen(a);
        getnext();
        top=0;
        stk[++top]=len;
        int x=len;
        while(x!=0){
            stk[++top]=next[x];
            x=next[x];
        }
        for(int i=top-1;i>0;i--){
            if(i!=top-1)printf(" ");
            printf("%d",stk[i]);
        }
        puts("");
    }
    return 0;
}
原文地址:https://www.cnblogs.com/lalalatianlalu/p/9640947.html