HDU1711 Number Sequence

题目链接

题解

对数字序列做一次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
#include <bits/stdc++.h>
using namespace std;
void build_fail(int *pat, int len, int *fail){
fail[0] = -1;
for(int i = 1, j = -1; i < len; ++i){
while(j > -1 && pat[i] != pat[j + 1])
j = fail[j];
if(pat[i] == pat[j + 1])
fail[i] = ++j;
else
fail[i] = -1;
}
}
int KMP_match(int *text, int l1, int *pat, int l2, int *fail){
for(int i = 0, j = -1; i < l1; ++i){
while(j > -1 && text[i] != pat[j + 1])
j = fail[j];
if(text[i] == pat[j + 1])
j++;
if(j == l2 - 1)
return i - l2 + 2;
}
return -1;
}
int n, m, a[1000005], b[10005], fail[10005] = {0};
int main(){
int T;
scanf("%d", &T);
while(T--){
scanf("%d%d", &n, &m);
for(int i = 0; i < n; ++i) scanf("%d", &a[i]);
for(int i = 0; i < m; ++i) scanf("%d", &b[i]);
build_fail(b, m, fail);
printf("%d\n", KMP_match(a, n, b, m, fail));
}
return 0;
}