【kmp+求所有公共前后缀长度】poj 2752 Seek the Name, Seek the Fame

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

【题意】

给定一个字符串,求这个字符串的所有公共前后缀的长度,按从小到达输出

【思路】

利用kmp的next数组,最后加上这个字符串本身

【AC】

 1 #include<iostream>
 2 #include<cstring>
 3 #include<string>
 4 #include<cstdio>
 5 #include<algorithm>
 6 using namespace std;
 7 typedef long long ll;
 8 
 9 const int maxn=4e5+3;
10 char str[maxn];
11 int nxt[maxn];
12 int ans[maxn];
13 void kmp_pre(char x[],int m,int nxt[])
14 {
15     int i,j;
16     j=nxt[0]=-1;
17     i=0;
18     while(i<m)
19     {
20         while(j!=-1&&x[i]!=x[j]) j=nxt[j];
21         nxt[++i]=++j;
22     }
23 }
24 
25 int main()
26 {
27     while(~scanf("%s",str))
28     {
29         memset(nxt,0,sizeof(nxt));
30         int len=strlen(str);
31         kmp_pre(str,len,nxt);
32         int cnt=0;
33         int x=len;
34         while(nxt[x])
35         {
36             ans[cnt++]=nxt[x];
37             x=nxt[x];
38         }
39         ans[cnt++]=len;
40         sort(ans,ans+cnt);
41         for(int i=0;i<cnt;i++)
42         {
43             if(i==0)
44                 printf("%d",ans[i]);
45             else
46                 printf(" %d",ans[i]);
47         }
48         puts("");
49     }
50     return 0;    
51 }
kmp
原文地址:https://www.cnblogs.com/itcsl/p/7398808.html