Given two sequences of numbers : a[1], a[2], …… , a[N], and b[1], b[2], …… , b[M] (1 <= M <= 10000, 1 <= N <= 1000000). Your task is to find a number K which make a[K] = b[1], a[K + 1] = b[2], …… , a[K + M – 1] = b[M]. If there are more than one K exist, output the smallest one. 

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

  1. 2
  2. 13 5
  3. 1 2 1 2 3 1 2 3 1 3 2 1 2
  4. 1 2 3 1 3
  5. 13 5
  6. 1 2 1 2 3 1 2 3 1 3 2 1 2
  7. 1 2 3 2 1

Sample Output

  1. 6
  2. -1
    代码:
  1. 1 #include <bits/stdc++.h>
  2. 2 using namespace std;
  3. 3 const int maxn = 1e6 + 10;
  4. 4 int n, m;
  5. 5 int a[maxn];
  6. 6 int b[maxn];
  7. 7 int nex[maxn];
  8. 8
  9. 9 void getnext()
  10. 10 {
  11. 11 int i = 1, j = 0;
  12. 12 nex[1] = 0;
  13. 13 while (i < m)
  14. 14 {
  15. 15 if (j == 0 || b[i] == b[j])
  16. 16 {
  17. 17 i++, j++;
  18. 18 if (b[i] != b[j]) nex[i] = j;
  19. 19 else nex[i] = nex[j];
  20. 20 }
  21. 21 else j = nex[j];
  22. 22 }
  23. 23 }
  24. 24
  25. 25 int kmp()
  26. 26 {
  27. 27 int i, j; i = j = 1;
  28. 28 while (i <= n && j <= m)
  29. 29 {
  30. 30 if (j == 0 || a[i] == b[j]) i++, j++;
  31. 31 else j = nex[j];
  32. 32 }
  33. 33 if (j > m)
  34. 34 return i - m;
  35. 35 else return -1;
  36. 36 }
  37. 37
  38. 38 int main()
  39. 39 {
  40. 40 int T; cin >> T;
  41. 41 while (T--)
  42. 42 {
  43. 43 cin >> n >> m;
  44. 44 for (int i = 1; i <= n; i++)
  45. 45 scanf("%d", a + i);
  46. 46 for (int i = 1; i <= m; i++)
  47. 47 scanf("%d", b + i);
  48. 48 getnext();
  49. 49 int res = kmp();
  50. 50 cout << res << endl;
  51. 51 }
  52. 52 }

 

  1.  

版权声明:本文为liuwenhan原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/liuwenhan/p/11445654.html