Seek the Name, Seek the Fame poj 2752(kmp&next数组的运用)

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数组即可。

#include<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>
using namespace std;
const int N=4e5+10;
char a[N];
int net[N],len,ans[N];
void getnext()
{
    net[0]=-1;
    int k=-1,j=0;
    while(j<len)
    {
        if(k==-1||a[j]==a[k])
            net[++j]=++k;
        else k=net[k];
    }
}
int main()
{
    int k;
    while(~scanf("%s",a))
    {
        k=0;
        len=strlen(a);
        getnext();
        for(int i=len;net[i]!=-1;i=net[i])
            ans[k++]=i;
        for(int i=k-1;i>=0;i--)
            printf(i==0?"%d\n":"%d ",ans[i]);
    }
}

猜你喜欢

转载自blog.csdn.net/never__give__up/article/details/80402778