Seek the Name, Seek the Fame
Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 9395 | Accepted: 4490 |
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
题意:求出既是字符串s的前缀又是s的后缀的子串长度。next[]值的应用:next[i]保存了以s[i]为结尾的后缀与模式串前缀的最长匹配数,所以这道题目可以从最后一个字符开始,设字符串长度为len,最后一个字符next[len-1]值即为符合题目要求的最长的子串长度,这样s的前next[len-1]个字符与后面next[len-1]个字符相同,所以我们下一次从第next[len-1]个字符开始遍历,以此类推。。
AC代码:
#include <iostream> #include <cstring> #include <cstdio> #include <queue> #include <cmath> #include <string> #include <algorithm> using namespace std; int next[400005]; void get_next(string a) { int len=a.length(); memset(next,0,sizeof(next)); for(int i=1;i<len;i++) { int temp=next[i-1]; while(temp&&a[temp]!=a[i]) temp=next[temp-1]; if(a[temp]==a[i]) next[i]=temp+1; else next[i]=0; } } int main() { string s; int ans[400005]; while(cin>>s) { int len=s.length(); get_next(s); int k=0; while(next[len-1]) { ans[k++]=next[len-1]; len=next[len-1]; } while(k--) { cout<<ans[k]<<" "; } cout<<s.length()<<endl; } return 0; }