HDU 1711 Number Sequence //简单kmp

忘是亡心i 2022-08-23 11:54 273阅读 0赞

Number Sequence

Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 10570 Accepted Submission(s): 4813

Problem Description

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.

Input

The 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].

Output

For 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

Source

HDU 2007-Spring Programming Contest

Recommend

lcy | We have carefully selected several similar problems for you: 1358 3336 3746 1251 2222

  1. #include <stdio.h>
  2. int a[10005], b[1000005], next[10005];
  3. void findnext(int m)
  4. {
  5. int i, j;
  6. i=0;
  7. j=-1;
  8. next[0] = -1;
  9. while(i<m)
  10. {
  11. if(j==-1 || a[i]==a[j])
  12. {
  13. i++;
  14. j++;
  15. next[i] = j;
  16. }
  17. else
  18. j = next[j];
  19. }
  20. }
  21. int main()
  22. {
  23. int t;
  24. int n, m;
  25. int i, j, flag;
  26. scanf("%d", &t);
  27. while(t--)
  28. {
  29. scanf("%d%d", &n, &m);
  30. for(i=0; i<n; i++)
  31. scanf("%d", &b[i]);
  32. for(i=0; i<m; i++)
  33. scanf("%d", &a[i]);
  34. findnext(m);
  35. flag = 0;
  36. i = 0;
  37. j = 0;
  38. while(i<n)
  39. {
  40. if(j==-1 || b[i]==a[j])
  41. {
  42. i++;
  43. j++;
  44. if(j>=m)
  45. {
  46. printf("%d\n", i-j+1);
  47. flag = 1;
  48. break;
  49. }
  50. }
  51. else
  52. j = next[j];
  53. }
  54. if(flag == 0)
  55. printf("-1\n");
  56. }
  57. return 0;
  58. }

发表评论

表情:
评论列表 (有 0 条评论,273人围观)

还没有评论,来说两句吧...

相关阅读