2724: Pku2752 Seek the Name, Seek the FameTime Limit: 1 Sec Memory Limit: 128 MB
Description
给定一个字符串,要求找到同时是它前缀也是后缀的字符串的个数,并且输出他们的长度。
Input
第一行一个数字N,第二行输入一个字符串,长度<= 10^6.
Output
输出这些子串的结束位置(因为它们的开始位置都是从1开始的),注意每个数字后面有一个空格
Sample Input
5
aaaaa
Sample Output
1 2 3 4 5
水题,考察。。嗯。。KMP中next数组的求值。
直接附上代码:
#include<bits/stdc++.h>
using namespace std;
char a[1000100];
int p[1000100];
int ans[1001000];
int main(){
int len;
scanf("%d",&len);
scanf("%s",a+1);
p[0]=1;
int j=0;
for(int i=1;i<=len;i++){
while(j>0&&a[i+1]!=a[j+1])j=p[j];
if(a[i+1]==a[j+1])j++;
p[i+1]=j;
}
/*for(int i=0;i<=len;i++){
printf("next[%d]=%d\n",i,p[i]);
}*/
j=len;
int i;
for(i=1;j>0;i++){
ans[i]=j;
j=p[j];
}
for(int k=i-1;k>1;k--)printf("%d ",ans[k]);
printf("%d",ans[1]);
return 0;
}
顺便附上友情链接
mg-class.github.io