poj 3461(KMP)

Poj 3461
纯KMP模板题,又复习了一下模板

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
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<vector>
#define ms(i,j) memset(i,j, sizeof i);
using namespace std;
const int MAXL = 1000000 + 5;
int T;
char s1[MAXL], s2[MAXL];
int f[MAXL];
void getfail()
{
f[0] = f[1] = 0;
int len = strlen(s2);
for (int i=1;i<len;i++)
{
int j = f[i];
while (j && s2[i]!=s2[j]) j = f[j];
f[i+1] = ((s2[i]==s2[j]) ? (j+1) : (0));
}
}
int kmp()
{
int ret = 0;
int len = strlen(s1);
int m = strlen(s2);
int j = 0;
for (int i=0;i<len;i++)
{
while (j && s1[i]!=s2[j]) j = f[j];
if (s1[i]==s2[j]) j++;
if (j==m) ret++;
}
return ret;
}
int main()
{
scanf("%d", &T);
while (T--)
{
scanf("%s%s", s2, s1);
getfail();
printf("%d\n", kmp());
}
return 0;
}

------ 本文结束 ------