Seek the Name, Seek the Fame
Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 8261 | Accepted: 3883 |
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:)
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.
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,求出str中存在多少子串,使得这些子串既是str的前缀,又是str的后缀。从小到大依次输出这些子串的长度。
大致思路:
如左图,假设黑色线来代表字符串str,其长度是len,红色线的长度代表next[len],根据next数组定义易得前缀的next[len]长度的子串和后缀next[len]长度的子串完全相同(也就是两条线所对应的位置)。我们再求出next[len]位置处的next值,也就是图中蓝线对应的长度。同样可以得到两个蓝线对应的子串肯定完全相同,又由于第二段蓝线属于左侧红线的后缀,所以又能得到它肯定也是整个字符串的后缀。
所以对于这道题,求出len处的next值,并递归的向下求出所有的next值,得到的就是答案。
1 #include<stdio.h> 2 #include<string.h> 3 4 int next[400005]; 5 char s[400005]; 6 int sum[400000]; 7 8 void get_next(int len) 9 { 10 int i,j; 11 i=0; 12 j=-1; 13 next[0]=-1; 14 while(i<len) 15 { 16 if(j==-1||s[i]==s[j]) 17 { 18 ++i; 19 ++j; 20 next[i]=j; 21 } 22 else 23 j=next[j]; 24 } 25 } 26 27 int main() 28 { 29 int len,i,k; 30 while(scanf("%s",s)!=EOF) 31 { 32 k=0; 33 len=strlen(s); 34 get_next(len); 35 for(i=len;i!=0;) 36 { 37 sum[k++]=next[i]; 38 i=next[i]; 39 } 40 for(i=k-2;i>=0;--i) 41 printf("%d ",sum[i]); 42 printf("%d\n",len); 43 } 44 return 0; 45 }