hdu 1711 Number Sequence

题目链接

题目含义:

给定两个整数序列,a 和 b ,从 a 序列中找 b 序列第一次出现的位置,如果存在输出第一次出现的位置,若不存在输出-1

思路:

将两个序列抽象成字符串的话,就是一个查找子串的问题,直接用KMP即可

#include <cstdio>
#include <cstdlib>
#include <algorithm>
using namespace std;
const int N = 1e6 + 10, M = 1e4 + 10;
int nex[M], a[N], b[M], n, m;
void get_next(){
	nex[0] = -1;
	int k = -1, i = 0;
	while (i < m){
		if(k == -1 || b[i] == b[k]){
			++i, ++k;
			nex[i] = k;
		}
		else k = nex[k];
	}
}
int kmp(){
	get_next();
	int i = 0, k = 0;
	while (i < n && k < m){
		if(k == -1 || a[i] == b[k]){
			++i, ++k;
		}
		else k = nex[k];
	}
	if(k == m)return i - m + 1;
	else return -1;
}
int main()
{
	int T;
	scanf("%d", &T);
	while (T--){
		scanf("%d %d", &n, &m);
		for (int i = 0; i < n; i++)scanf("%d", &a[i]);
		for (int i = 0; i < m; i++)scanf("%d", &b[i]);
		printf("%d\n", kmp());
	}
	return 0;
}

 

posted @ 2019-08-26 16:22  correct  阅读(68)  评论(0)    收藏  举报