码迷,mamicode.com
首页 > 其他好文 > 详细

Seek the Name, Seek the Fame(Kmp)

时间:2015-08-07 16:01:45      阅读:98      评论:0      收藏:0      [点我收藏+]

标签:

Seek the Name, Seek the Fame

Time Limit : 4000/2000ms (Java/Other)   Memory Limit : 131072/65536K (Java/Other)
Total Submission(s) : 12   Accepted Submission(s) : 7
Problem 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
 题解:
    技术分享如左图,假设黑色线来代表字符串str,其长度是len,红色线的长度代表next[len],根据next数组定义易得前缀的next[len]长度的子串和后缀next[len]长度的子串完全相同(也就是两条线所对应的位置)。我们再求出next[len]位置处的next值,也就是图中蓝线对应的长度。同样可以得到两个蓝线对应的子串肯定完全相同,又由于第二段蓝线属于左侧红线的后缀,所以又能得到它肯定也是整个字符串的后缀。

    所以对于这道题,求出len处的next值,并递归的向下求出所有的next值,得到的就是答案。

所以每次只需要找此段匹配的长度就好

代码:用了个递归,浪了一下,竟然还没PE;

 1 #include<stdio.h>
 2 #include<string.h>
 3 const int MAXN=400010;
 4 char s[MAXN];
 5 int p[MAXN],len;
 6 void getp(){
 7     int i=0,j=-1;
 8     p[0]=-1;
 9     while(i<len){
10         if(j==-1||s[i]==s[j]){
11             i++;j++;
12             p[i]=j;
13         }
14         else j=p[j];
15     }
16 }
17 void print(int x){
18     if(x<=0)return;
19     print(p[x]);
20     printf("%d ",x);
21 }
22 int main(){int i,j;
23     while(~scanf("%s",s)){
24         len=strlen(s);
25         getp();
26         /*for(i=0;i<=len;i++)printf("%d ",p[i]);puts("");
27         j=len;
28         while(j>=0){
29             for(i=p[j];i<j;i++)printf("%c",s[i]);puts("");
30             j=p[j];
31         }*/
32         print(len);puts("");
33     }
34     return 0;
35 }

 

Seek the Name, Seek the Fame(Kmp)

标签:

原文地址:http://www.cnblogs.com/handsomecui/p/4711034.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!