Seek the Name, Seek the Fame
Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 24947 | Accepted: 12995 |
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
问题链接:POJ2752 Seek the Name, Seek the Fame
问题描述:对于字符串S。问公共前缀后缀的长度有哪些。
解题思路:KMP算法的next数组的应用,next[len]表示字符串S的最长公共前缀后缀,而问题还要求可能存在的更小的公共前缀后缀的长度,在求next数组时,当发生失配时,我们通过k=next[k]去寻找更小的公共前缀后缀。那么我们求出next[len]后可以主动使用k=next[k]去寻找,具体看程序。
AC的C++程序:
#include<iostream>
#include<algorithm>
#include<vector>
#include<cstring>
using namespace std;
const int N=400010;
char p[N];
int Next[N];
vector<int>v;
void GetNext(char p[],int next[])
{
next[0]=-1;
int k=-1,j=0,plen=strlen(p);
while(j<plen)
{
//p[k]表示前缀 p[j]表示后缀
if(k==-1||p[k]==p[j])
{
k++;
j++;
next[j]=k;
}
else
k=next[k];
}
v.clear();
while(next[j]>0) //寻找更小的公共前缀后缀长度
{
v.push_back(next[j]);
j=next[j];
}
sort(v.begin(),v.end());
for(int i=0;i<v.size();i++)
printf("%d ",v[i]);
printf("%d\n",plen);//本身
}
int main()
{
while(~scanf("%s",p))
{
GetNext(p,Next);
}
return 0;
}