一个可以优雅地使用kmp解决的问题_hdu4763

巧妙地利用配函数 f

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47

#include <cstring>
#include <algorithm>
#include <iostream>
using namespace std;
const int maxn=1e6+10;
int f[maxn],vis[maxn];
char p[maxn];

void (){
f[0]=f[1]=0;
int m=strlen(p);
for(int i=1;i<m;i++){
int j=f[i];
while(j&&p[i]!=p[j]) j=f[j];
f[i+1]=p[i]==p[j]?j+1:0;
}
}


void show(){
int m=strlen(p);
for(int i=0;i<=m;i++) printf("%4c",p[i]);
cout<<endl;
for(int i=0;i<=m;i++) printf("%4d",f[i]);
cout<<endl;
}


int T;
int main(){
cin>>T;
while(T--){
scanf(" %s",p);
getfail();

memset(vis,0,sizeof(vis));
int m=strlen(p);
for(int i=0;i<m;i++) vis[f[i]]=1;
int j=f[m];
while(vis[j]==0) j=f[j];
cout<<j<<"n";

}

return 0;
}