Number Sequence HDU - 1711(KMP匹配)
【摘要】
题目:
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
代码:
-
#include<iostream>
-
#include<string.h>
-
using namespace std;
-
-
int listn[1000001]; //长串
-
int listm[10001]; //短串
-
int next_[10001];
-
-
void getnext(int *t,int m, int *next) //m是短串t的长度
-
{
-
int i = 1, j = 0;
-
next[1] = 0;
-
while (i < m)
-
{
-
if (j == 0 || t[i] == t[j])
-
{
-
i++;
-
j++;
-
if (t[i] != t[j])next[i] = j;
-
else next[i] = next[j];
-
}
-
else j = next[j];
-
}
-
}
-
-
int main()
-
{
-
ios_base::sync_with_stdio(false); //减小输入输出的时间
-
int t, n, m;
-
cin >> t;
-
while (t--)
-
{
-
cin >> n >> m;
-
for (int i = 1; i <= n; i++)cin >> listn[i];
-
for (int i = 1; i <= m; i++)cin >> listm[i];
-
listm[0] = 2000000;
-
next_[0] = 0;
-
next_[1] = 0;
-
int i,j;
-
getnext(listm, m, next_);
-
i = 1;
-
j = 1;
-
while (i <= n)
-
{
-
if (listn[i] == listm[j])
-
{
-
i++;
-
j++;
-
if (j > m)break;
-
}
-
else
-
{
-
if (next_[j])j = next_[j];
-
else
-
{
-
i++;
-
j = 1;
-
}
-
}
-
}
-
if (j > m)cout << i - m;
-
else cout << -1;
-
cout << endl;
-
}
-
return 0;
-
}
文章来源: blog.csdn.net,作者:csuzhucong,版权归原作者所有,如需转载,请联系作者。
原文链接:blog.csdn.net/nameofcsdn/article/details/79691556
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)