`
Coco_young
  • 浏览: 120004 次
  • 性别: Icon_minigender_1
  • 来自: 湖南长沙
社区版块
存档分类
最新评论

[KMP-NEXT数组性质]POJ 2752 Seek the Name, Seek the Fame

 
阅读更多

传送门:http://poj.org/problem?id=2752

题目描述:要求求出字符串S所有满足如下条件的子串长度(1.子串T为S的前缀 2.子串T为S的后缀)。

解题思路:利用KMP的NEXT数组的特性,Next[pos]的含义是在pos处失配时pos应该指向的下一个位置,那么0-(Next[pos]-1)构成的字符串和(pos-Next[pos])-(pos-1)构成的字符串是相同么,那么即0-(Next[pos]-1)构成的字符串是,0-pos-1构成的字符串的前缀后缀子串,这样,考虑在主串S后面增加一个字符,构成新字符串P,那么求出P最后一个位置的Next[]值,那么就可以按照上述分析来求出前缀后缀子串(PS:要把pos不停的滑动,直到pos=0,因为空串不算是前缀后缀子串)


代码:

#include<iostream>
#include<cstring>
#include<cstdio>
#include<vector>
using namespace std;
const int MAXN = 4111111;
char P[MAXN];
int Next[MAXN],M;
vector<int> ans;
void MakeNext(int M){
    int i = 0, j = -1;
    Next[0] = -1;
    while(i<M){
        if(j==-1||P[i]==P[j])Next[++i]=++j;
        else j = Next[j];
    }
}
int main(){
    while(scanf("%s",P)!=EOF){
        M = strlen(P);
        P[M] = '5';P[++M]=0;
        ans.clear();
        MakeNext(M);
        int pos = M-1;
        while(pos){
            ans.push_back(pos);
            pos = Next[pos];
        }
        for(int i=(int)ans.size()-1;i>=0;i--){
            if(i)printf("%d ",ans[i]);
            else printf("%d\n",ans[i]);
        }
    }
    return 0;
}


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics