Seek the Name, Seek the Fame

poj2752:http://poj.org/problem?id=2752

题意:给你一个串,让你求前n个字符和后n个字符相同的n有多少,从小到大输出来。

题解:这一题要深刻理解KMP的next数组,只有深刻理解,才能觉得比较轻松。推荐一个人的博客,这个人讲的比较好。

http://blog.csdn.net/zhang20072844/article/details/5779452

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 #include<algorithm>
 5 using namespace std;
 6 const int N=400000+5;
 7 int f[N],num[N],top;
 8 char s[N];
 9 int main(){
10    while(~scanf("%s",s)){
11       f[0]=f[1]=0;top=0;
12       int len=strlen(s);
13       for(int i=1;i<len;i++){
14         int j=f[i];
15         while(j&&s[j]!=s[i])j=f[j];
16         f[i+1]=(s[j]==s[i]?j+1:0);
17       }
18       int j=f[len];
19       num[++top]=len;
20       while(j!=0){
21          num[++top]=j;
22          j=f[j];
23       }
24       for(int i=top;i>=1;i--){
25         if(i==top)printf("%d",num[i]);
26         else
27         printf(" %d",num[i]);
28       }
29          printf("\n");
30    }
31 }
View Code

posted on 2014-07-19 20:51  天依蓝  阅读(149)  评论(0编辑  收藏  举报

导航