POJ 2752 Seek the Name, Seek the Fame

题目:

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
题意描述:
输入一个字符串
计算并输出该串既是前缀又是后缀的子串的长度
比如alala
前缀有a,al,ala,alal,alala
后缀有a,la,ala,lala,alala
所以既是前缀又是后缀的有a,ala,alala
所以应该输出1,3,5
解题思路:
属于KMP中next[]数组的应用。显然枚举每一个前后缀相同时输出并不是什么好办法,我们将题中alalal的前后缀写出来,比较出相同的,在写出其next数组,会发现:前后缀的相似度和前后缀相同时的长度存在关联。
细心就会发现,next末位存的是串的前后缀都是串本身时的相似度,也就是相同长度,而next数组末位中存的又是下一个相同长度时的next数组下标,依次类推,直到相似度为0。
代码实现:
 1 #include<stdio.h>
 2 #include<string.h>
 3 char s[400010];
 4 int get_next(char t[],int next[],int l);
 5 int ans[400010],l,next[400010];
 6 int main()
 7 {
 8     int i,j,t,c;
 9     while(scanf("%s",s) != EOF)
10     {
11         l=strlen(s);
12         memset(next,0,sizeof(next));
13         get_next(s,next,l);
14         
15         t=next[l];
16         ans[0]=l;
17         c=1;
18         while(t != 0)
19         {
20             ans[c++]=t;
21             t=next[t]; 
22         }
23         for(i=c-1;i>=0;i--)
24         {
25             if(i==c-1)
26             printf("%d",ans[i]);
27             else
28             printf(" %d",ans[i]);
29         }
30         printf("\n");
31     }
32     return 0;
33 }
34 int get_next(char t[],int next[],int l)
35 {
36     int i,j;
37     i=0;j=-1;
38     next[0]=-1;
39     while(i < l)
40     {
41         if( j==-1 || t[i]==t[j])
42         {
43             i++;
44             j++;
45             next[i]=j;
46         }
47         else
48             j=next[j];
49     }
50     /*for(i=0;i<=l;i++)
51         printf("%d ",next[i]);
52     printf("\n");*/
53 }

 

posted @ 2017-08-11 11:27  Reqaw  阅读(179)  评论(0编辑  收藏  举报