Seek the Name, Seek the Fame
Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 24954 | Accepted: 13001 |
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:)
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.
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,但next[i]数组是求最大前缀和后缀的怎么办?
其实看下图:
假如abbaabbabb
我们实现这个字符串自身匹配过程
第一个过程:
a b b|a b b a b b|
|a b b a b b|a b b
| |之间字符长度为6
第二个过程:
a b ba b b |a b b|
|a b b |a b b a b b
| |之间字符长度为3
3 6 9(本身) 就是答案
这个匹配过程就相当于递归k=nxt[k]
代码:
#include<cstdio>
#include<iostream>
#include<fstream>
#include<algorithm>
#include<functional>
#include<cstring>
#include<string>
#include<cstdlib>
#include<iomanip>
#include<numeric>
#include<cctype>
#include<cmath>
#include<ctime>
#include<queue>
#include<stack>
#include<list>
#include<set>
#include<map>
using namespace std;
const int N = 1000002;
int nxt[N];
string S,T,T1;
int tlen;
void getNext()
{
int j, k;
j = 0; k = -1;
nxt[0] = -1;
while(j < tlen)
if(k == -1 || T[j] == T[k])
{
nxt[++j] = ++k;
if (T[j] != T[k])
nxt[j] = k;
}
else
k = nxt[k];
}
int main()
{
while(cin>>T)
{
tlen= T.length();
getNext();
vector<int> ans;
ans.push_back(tlen);
int k=nxt[tlen];
while(k>0)
{
ans.push_back(k);
k=nxt[k];
}
for(int i=ans.size()-1;i>=0;i--)
{
printf("%d ",ans[i]);
}
cout<<endl;
}
return 0;
}