Number Sequence HDU - 1711 (KMP模板题)
InputThe first line of input is a number T which indicate the number of cases. Each case contains three lines. The first line is two numbers N and M (1 <= M <= 10000, 1 <= N <= 1000000). The second line contains N integers which indicate a[1], a[2], …… , a[N]. The third line contains M integers which indicate b[1], b[2], …… , b[M]. All integers are in the range of [-1000000, 1000000].
OutputFor each test case, you should output one line which only contain K described above. If no such K exists, output -1 instead.
Sample Input
- 2
- 13 5
- 1 2 1 2 3 1 2 3 1 3 2 1 2
- 1 2 3 1 3
- 13 5
- 1 2 1 2 3 1 2 3 1 3 2 1 2
- 1 2 3 2 1
Sample Output
- 6
- -1
代码:
- 1 #include <bits/stdc++.h>
- 2 using namespace std;
- 3 const int maxn = 1e6 + 10;
- 4 int n, m;
- 5 int a[maxn];
- 6 int b[maxn];
- 7 int nex[maxn];
- 8
- 9 void getnext()
- 10 {
- 11 int i = 1, j = 0;
- 12 nex[1] = 0;
- 13 while (i < m)
- 14 {
- 15 if (j == 0 || b[i] == b[j])
- 16 {
- 17 i++, j++;
- 18 if (b[i] != b[j]) nex[i] = j;
- 19 else nex[i] = nex[j];
- 20 }
- 21 else j = nex[j];
- 22 }
- 23 }
- 24
- 25 int kmp()
- 26 {
- 27 int i, j; i = j = 1;
- 28 while (i <= n && j <= m)
- 29 {
- 30 if (j == 0 || a[i] == b[j]) i++, j++;
- 31 else j = nex[j];
- 32 }
- 33 if (j > m)
- 34 return i - m;
- 35 else return -1;
- 36 }
- 37
- 38 int main()
- 39 {
- 40 int T; cin >> T;
- 41 while (T--)
- 42 {
- 43 cin >> n >> m;
- 44 for (int i = 1; i <= n; i++)
- 45 scanf("%d", a + i);
- 46 for (int i = 1; i <= m; i++)
- 47 scanf("%d", b + i);
- 48 getnext();
- 49 int res = kmp();
- 50 cout << res << endl;
- 51 }
- 52 }