HDU1711-Number Sequence

系统管理员 2022-06-03 04:40 264阅读 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

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

发表评论

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

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

相关阅读