Seek the Name, Seek the Fame
Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 9153 | Accepted: 4338 |
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
Source
POJ Monthly--2006.01.22,Zeyuan Zhu
这道题着实让我这个初识KMP的菜鸟纠结了好久 想通之后发现 对KMP的理解又深刻了很多 。
本题让我们找出既是前缀又是后缀的字符串长度(可以这么理解),在GetNext()上要有一点变化 就是求出next[len]这种情况。
next[len]的意义不可小觑,它代表着整个字符串中最长的那个符合题意的字串的长度。
比如说 ababcababababcabab 中next[len]=9 令s1=ababcabab s2=ababcabab
这就说明整个字符串中 s1与s2是匹配的。
既然这样 我们可以把s1看成一个新的字符串 s1=ababcabab
这个串中既是前缀又是后缀的串 在s2=ababcabab中也一定是后缀。
这样向前寻找 直到next[k]==0 再反向输出即可 , 当然 千万别忘了整个字符串 它也满足既是前缀 又是后缀的条件~
#include<iostream>
using namespace std;
char thestr[400020];
int thenext[400020];
int theans[400020];
void getnext(char str[],int next[]){
int j = 0;
int k = -1;
int len = strlen(str);
next[0]=-1;
while(j<len+1){
if(k==-1||str[j]==str[k]){
k++;
j++;
next[j]=k;
}
else{
k = next[k];
}
}
}
int main(){
while(scanf("%s",thestr)!=EOF){
getnext(thestr,thenext);
int len = strlen(thestr);
int i = 1 ;
int j = len ;
theans[0]=len;
while(thenext[j]!=0){
int k = thenext[j];
theans[i++]=k;
j=k;
}
for(i=i-1;i>=0;i--){
cout<<theans[i]<<' ';
}
cout<<endl;
}
}