POJ-2752()(KMP)(Seek the Name, Seek the Fame)
Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 15833 | Accepted: 8039 |
Description
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
Restrictions: Only lowercase letters may appear in the input. 1 <= Length of S <= 400000.
Output
Sample Input
ababcababababcabab aaaaa
Sample Output
2 4 9 18 1 2 3 4 5
My soution:
/*2016.4.12*/
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
char c[400010];
int nest[400010],len,cnt[400010];
void getnest()
{
int i=0,j=-1,k;
nest[0]=-1;
len=strlen(c);
while(i<len)
{
if(j==-1||c[i]==c[j])
{
i++,j++;
nest[i]=j;
}
else
j=nest[j];
}
return ;
}
void solve()
{
int i=1,j,k,y,x;
getnest();
x=len-1;y=nest[x];
while(y!=-1)
{
if(c[x]==c[y])
cnt[i++]=y+1;//記錄子串長度
y=nest[y];//遞歸
}
cnt[0]=len;//字符串本身也滿足前綴、後綴相等
for(j=i-1;j>0;j--)
printf("%d ",cnt[j]);
printf("%d\n",cnt[0]);
}
int main()
{
int i,j;
while(scanf("%s",c)!=EOF)
{
solve();
}
return 0;
}