Hdu 1711(KMP)

hdu 1711
1、KMP的数组下标从0开始

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
48
49
50
51
52
53
54
55
56
57
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<vector>
using namespace std;
#define ms(i,j) memset(i, j, sizeof i);
const int MAXN = 1000000 + 5, MAXM = 10000 + 5;
int f[MAXM], s1[MAXN], s2[MAXM];
int n, m;
void init()
{
scanf("%d%d", &n, &m);
for (int i=0;i<n;i++)
{
scanf("%d", &s1[i]);
}
for (int i=0;i<m;i++)
{
scanf("%d", &s2[i]);
}
}
void solve()
{
f[0] = f[1] = 0;
for (int i=1;i<m;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 j = 0;
for (int i=0;i<n;i++)
{
while (j && s1[i]!=s2[j]) j = f[j];
if (s1[i]==s2[j]) j++;
if (j==m)
{
printf("%d\n", i-m+1+1);
return ;
}
}
printf("-1\n");
}
int main()
{
int t;
scanf("%d", &t);
while (t--)
{
init();
solve();
}
return 0;
}

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