Seek the Name, Seek the Fame---poj2752(kmp中的Next数组)

题目链接:http://poj.org/problem?id=2752

题意就是求出是已知s串的前缀的长度x,并且要求此前缀也是s串的后缀;求出所有的 x ;

Next【i】的含义是前i个元素的前缀和后缀的最大匹配;

所以本题就很简单了。。。

#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<string.h>
using namespace std;

const int N = 4*1e5+7;

char s[N];
int Next[N], n, a[N];

void GetNext()
{
    int i=0, j=-1;
    Next[0] = -1;
    while(i<n)
    {
        if(j==-1 || s[i] == s[j])
            Next[++i] = ++j;
        else
            j=Next[j];
    }
}
int main()
{
    int i;
    while(scanf("%s", s)!=EOF)
    {
        n = strlen (s);
        GetNext();
        a[0] = n;
        i=1;
        while(Next[a[i-1]]!=0)
        {
            a[i] = Next[a[i-1]];
            i++;
        }
        sort(a, a+i);
        for(int j=0; j<i; j++)
            printf("%d%c", a[j], i-1==j?'
':' ');
    }
    return 0;
}
View Code
原文地址:https://www.cnblogs.com/zhengguiping--9876/p/4835532.html