Number Sequence HDU - 1711(KMP匹配)

举报
用户已注销 发表于 2021/11/19 04:15:45 2021/11/19
【摘要】 题目: 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...

题目:

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. 


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
6
-1


代码:


  
  1. #include<iostream>
  2. #include<string.h>
  3. using namespace std;
  4. int listn[1000001]; //长串
  5. int listm[10001]; //短串
  6. int next_[10001];
  7. void getnext(int *t,int m, int *next) //m是短串t的长度
  8. {
  9. int i = 1, j = 0;
  10. next[1] = 0;
  11. while (i < m)
  12. {
  13. if (j == 0 || t[i] == t[j])
  14. {
  15. i++;
  16. j++;
  17. if (t[i] != t[j])next[i] = j;
  18. else next[i] = next[j];
  19. }
  20. else j = next[j];
  21. }
  22. }
  23. int main()
  24. {
  25. ios_base::sync_with_stdio(false); //减小输入输出的时间
  26. int t, n, m;
  27. cin >> t;
  28. while (t--)
  29. {
  30. cin >> n >> m;
  31. for (int i = 1; i <= n; i++)cin >> listn[i];
  32. for (int i = 1; i <= m; i++)cin >> listm[i];
  33. listm[0] = 2000000;
  34. next_[0] = 0;
  35. next_[1] = 0;
  36. int i,j;
  37. getnext(listm, m, next_);
  38. i = 1;
  39. j = 1;
  40. while (i <= n)
  41. {
  42. if (listn[i] == listm[j])
  43. {
  44. i++;
  45. j++;
  46. if (j > m)break;
  47. }
  48. else
  49. {
  50. if (next_[j])j = next_[j];
  51. else
  52. {
  53. i++;
  54. j = 1;
  55. }
  56. }
  57. }
  58. if (j > m)cout << i - m;
  59. else cout << -1;
  60. cout << endl;
  61. }
  62. return 0;
  63. }

文章来源: blog.csdn.net,作者:csuzhucong,版权归原作者所有,如需转载,请联系作者。

原文链接:blog.csdn.net/nameofcsdn/article/details/79691556

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。