POJ 2752 Seek the Name, Seek the Fame

Posted Mr_Wolfram的高维空间

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了POJ 2752 Seek the Name, Seek the Fame相关的知识,希望对你有一定的参考价值。

这是一道利用KMP中next数组性质的题目,next[i]表示在字符串s中在i位置之前的的字符中的最大公共前缀后缀,那么我们就从nxt[len-1]开始
令k=nxt[len-1]判断是s[k]与s[len-1]是否相等,若相等则存下来,然后k=nxt[k],字符串的前缀一定是前缀的前缀。

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cstdlib>
#include <cmath>
using namespace std;
const int MAXN=400000+5;
int init(){
    int rv=0,fh=1;
    char c=getchar();
    while(c<'0'||c>'9'){
        if(c=='-') fh=-1;
        c=getchar();
    }
    while(c>='0'&&c<='9'){
        rv=(rv<<1)+(rv<<3)+c-'0';
        c=getchar();
    }
    return fh*rv;
}
char s[MAXN];
int nxt[MAXN],cnt[MAXN],num;
void getnxt(){
    nxt[0]=-1;
    int k=-1,j=0,len=strlen(s);
    while(j<len){
        if(k==-1||s[j]==s[k]){
            nxt[++j]=++k;
        }else k=nxt[k];
    }
}
int main(){
    freopen("in.txt","r",stdin);
    while(scanf("%s",s)==1){
        getnxt();
        num=0;
        int len=strlen(s);
        int k=nxt[len-1];
        while(k!=-1){
            if(s[k]==s[len-1]) cnt[++num]=k+1;
            k=nxt[k];
        }
        for(int i=num;i>=1;i--) printf("%d ",cnt[i]);
        printf("%d\n",len);
    }
    fclose(stdin);
    return 0;
}

以上是关于POJ 2752 Seek the Name, Seek the Fame的主要内容,如果未能解决你的问题,请参考以下文章

POJ 2752 Seek the Name, Seek the Fame(KMP求公共前后缀)

POJ 2752 Seek the Name, Seek the Fame

POJ2752 Seek the Name, Seek the Fame

POJ 2752 Seek the Name, Seek the Fame

poj2752 Seek the Name, Seek the Fame

poj 2752 Seek the Name, Seek the Fame