Seek the Name, Seek the Fame
Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 22934 | Accepted: 11947 |
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
题意是这样的 它给你一个串 问你对应所有后缀 它的相同前缀长度是多少?
那么我们整个就可以当作一个前后缀(都是)
现在我们怎么求这一过程中所有前缀呢?
我们要知道KMP算法有这么一个性质
性质2:kmp的next不断向前递归的过程可以保证对于每一个当前前缀,都有一段后缀与之对应
那么我们显而易得 我们只要拿整个字符串的长度当作tmp 用tmp去向前递归 根据这一性质 一定会有相同后缀
那么求得的不就是答案了吗?
#include <cstdio>
#include <cstring>
#include <cmath>
#include <iostream>
#include <algorithm>
using namespace std;
const int MAX_N = 400001;
int Next[MAX_N];
int ans[MAX_N];
char mo[MAX_N];
int n2;
void getnext(){
int i=0,j=-1;
while(i<n2){
if(j==-1||mo[i]==mo[j]) {++i,++j,Next[i]=j;}
else j = Next[j];
}
return ;
}
int main(){
while(~scanf("%s",mo)){
n2=strlen(mo);
Next[0] = -1;
getnext();
int cnt = 0;
int tmp = n2;
while(tmp!=0){
ans[cnt++] = tmp;
tmp=Next[tmp];
}
for(int i=cnt-1;i>=0;i--)
i==0?printf("%d\n",ans[i]):printf("%d ",ans[i]);
}
return 0;
}