【KMPnxt数组应用】POJ2752Seek the Name, Seek the Fame

Seek the Name, Seek the Fame
Time Limit: 2000MS        Memory Limit: 65536K
Total Submissions: 25118        Accepted: 13080
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
Source

POJ Monthly--2006.01.22,Zeyuan Zhu
T

这道题就是求所有前缀,使这个前缀同时也是这个词的后缀

依旧是KMP,用手画一画即可得知只要一直一直跳nxt输出就行

 1 #include<cstdio>
 2 #include<algorithm>
 3 #include<cstring>
 4 #define N 400000+1000
 5 using namespace std;
 6 char a[N];
 7 int nxt[N],len,ans[N],pp;
 8 void getnxt()
 9 {
10     int j=1,k=0;
11     while(j<=len)
12     {
13         if(k==0||a[j]==a[k])
14             j++,k++,nxt[j]=k;
15         else 
16             k=nxt[k];
17     }
18 }
19 int main()
20 {
21     while(scanf("%s",a+1)!=EOF)
22     {
23         memset(nxt,0,sizeof(nxt)),pp=0;
24         len=strlen(a+1);
25         getnxt();
26         for(int i=len+1;i;i=nxt[i])
27             ans[++pp]=i-1;
28         //if(a[1]==a[len])printf("1 ");
29         for(int i=pp;i>=1;i--)
30             if(ans[i])printf("%d ",ans[i]);
31         printf("
"); 
32     }
33     return 0;
34 }
原文地址:https://www.cnblogs.com/Qin-Wei-Kai/p/10209058.html