POJ 2752 Seek the Name, Seek the Fame(KMP)

题意

给出一个字符串问有多少长度,使这个长度的前缀等于这个长度的后缀。

n<=400000

题解

考虑nxt数组的意义。我们发现构建nxt数组时,一直跳nxt数组就是在枚举,所有前缀和后最相等的长度。

所以我们求出nxt数组,然后一直跳nxt[len]就好了。

 1 #include<iostream>
 2 #include<cstring>
 3 #include<cstdio>
 4 #include<cmath>
 5 #include<algorithm>
 6 using namespace std;
 7 const int N=500000;
 8 char s[N];
 9 int nxt[N],ans[N];
10 void dfs(int x){
11     if(nxt[x]<=0)return;
12     dfs(nxt[x]);
13     printf("%d ",nxt[x]);
14 }
15 int main(){
16     while(scanf("%s",s+1)!=EOF){
17         int len=strlen(s+1);
18             nxt[1]=0;
19             for(int i=2,j=0;i<=len;i++){
20             while(j&&s[j+1]!=s[i])j=nxt[j];
21             if(s[j+1]==s[i])j++;
22             nxt[i]=j;
23         }
24         dfs(len);
25         printf("%d
",len);
26     }
27     return 0;
28 }
原文地址:https://www.cnblogs.com/Xu-daxia/p/9516692.html