POJ 2752 Seek the Name, Seek the Fame(KMP中next数组的运用)

题目链接

Description

The little cat is so famous, that many couples tramp over hill and dale to Byteland, and asked the little cat to give names to their newly-born babies. They seek the name, and at the same time seek the fame. In order to escape from such boring job, the innovative little cat works out an easy but fantastic algorithm: 

Step1. Connect the father's name and the mother's name, to a new string S. 
Step2. Find a proper prefix-suffix string of S (which is not only the prefix, but also the suffix of S). 

Example: Father='ala', Mother='la', we have S = 'ala'+'la' = 'alala'. Potential prefix-suffix strings of S are {'a', 'ala', 'alala'}. Given the string S, could you help the little cat to write a program to calculate the length of possible prefix-suffix strings of S? (He might thank you by giving your baby a name:) 

Input

The input contains a number of test cases. Each test case occupies a single line that contains the string S described above. 

Restrictions: Only lowercase letters may appear in the input. 1 <= Length of S <= 400000. 

Output

For each test case, output a single line with integer numbers in increasing order, denoting the possible length of the new baby's name.

Sample Input

ababcababababcabab
aaaaa

Sample Output

2 4 9 18
1 2 3 4 5

题意:给出一个字符串,求出该字符串所有相同前后缀的长度。

题解:这个题就是next数组的简单运用,next数组,例如:第i位保存的是数组前i个字符中最长的相同前后缀长度,len为输入字符串的长度,next[len]为整个字符串的最长相同前后缀长度。后面一直递归到公共长度为0时的所有值都是该字符串的相同前后缀的长度,若是不懂可以参考这篇博客。传送门

#include <iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<map>
#include<queue>
#include<set>
#include<cmath>
#include<stack>
#include<string>
const int maxn=4e5+10;
const int mod=10007;
const int inf=1e8;
#define me(a,b) memset(a,b,sizeof(a))
#define lowbit(x) x&(-x)
typedef long long ll;
using namespace std;
char str[maxn];
int nex[maxn];
int main()
{
    while(scanf("%s",str)!=EOF)
    {
        int len=strlen(str);
        nex[0]=nex[1]=0;
        for(int i=1; i<len; i++)///求next数组
        {
            int k=nex[i];
            while(k&&str[i]!=str[k])
                k=nex[k];
            nex[i+1]=str[i]==str[k]?++k:0;
        }
        int ans[maxn],l=0,temp=len;
        while(nex[temp])///求所有相同前后缀长度
        {
            ans[l++]=nex[temp];
            temp=nex[temp];
        }
        for(int i=l-1;i>=0;i--)
            printf("%d ",ans[i]);
        printf("%d\n",len);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41292370/article/details/85785683