HDU - 1711 Number Sequence (KMP)

ゞ 浴缸里的玫瑰 2022-05-19 07:50 355阅读 0赞

Number Sequence

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

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

题意描述:

在序列A中找到序列B的位置,若不包含序列B输出-1.

解题思路:

完全kmp算法模板题,先求出序列B的next[]数组,再利用KMP算法求出位置定义一个flag若不包含输出-1.

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

发表评论

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

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

相关阅读