洛谷日刷-KMP算法 | Eternal_zttz

洛谷日刷-KMP算法

P3371 P3366 【模板】最小生成树

洛谷传送门

AC代码:

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
#include <cstdio>
#include <cstring>
#define maxN 1000001
#define maxM 2001
#define inf 247493646
int n,m;
int next[maxN];
char A[maxN],B[maxN];
int main(){
scanf("%s",A);
scanf("%s",B);
n = strlen(A);
m = strlen(B);
next[0] = -1;
for (int i = 1;i<m;i++){
int j = next[i-1];
while((B[j+1]!=B[i])&&(j>=0))
j = next[j];
if(B[j+1] == B[i])
next[i] = j+1;
else
next[i] = -1;
}
int i = 0,j = 0;
while(i<n){
if(A[i] == B[j]){
i++;j++;
if(j == m){
printf("%d\n",i-m+1);
j = next[j-1]+1;
}
}
else{
if(j == 0)
i++;
else
j = next[j-1]+1;
}
}
for (int i = 0;i<m;i++)
printf("%d ",next[i]+1);
printf("\n");
return 0;
}
-------------The End-------------