kmp算法。
1 #include <cstdio>
2 #include <cstring>
3
4 char src[10005], des[1000005];
5 int next[10005], total;
6
7 void kmp(char des[], char src[]){
8 int ld = strlen(des);
9 int ls = strlen(src);
10 int i, j;
11
12 total = i = j = 0;
13 while (i < ld) {
14 if (des[i] == src[j]) {
15 ++i;
16 ++j;
17 } else {
18 j = next[j];
19 if (j == -1) {
20 j = 0;
21 ++i;
22 }
23 }
24 if (j == ls) {
25 ++total;
26 j = next[j];
27 }
28 }
29 }
30
31 void getnext(char src[]) {
32 int i=0, j = -1;
33 next[0] = -1;
34 while (i < strlen(src)) {
35 if (j==-1 || src[i]==src[j]) {
36 ++i;
37 ++j;
38 next[i] = j;
39 } else {
40 j = next[j];
41 }
42 }
43 }
44
45 int main() {
46 int n;
47
48 scanf("%d", &n);
49 while (n--) {
50 scanf("%s",src);
51 scanf("%s",des);
52 getnext(src);
53 kmp(des, src);
54 printf("%d\n", total);
55 }
56
57 return 0;
58 }
【HDOJ】1686 Oulipo,布布扣,bubuko.com
时间: 2024-12-25 15:32:45