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 }