hdu1711

/**/
#include <cstdio>
#include <cstring>
#include <cmath>
#include <cctype>
#include <iostream>
#include <algorithm>
#include <map>
#include <set>
#include <vector>
#include <string>
#include <stack>
#include <queue>

typedef long long LL;
using namespace std;

int t;
int n, m;
int a[1000005], b[10005];
int fail[10005];

void getfail(int p[]){
	int x = -1;
	fail[0] = -1;
	for (int i = 1; i < m; i++){
		while(x >= 0 && p[x + 1] != p[i]){
			x = fail[x];
		}
		if(p[x + 1] == p[i]) x++;
		fail[i] = x;
	}
}

void KMP(int q[], int p[]){
	int x = -1;
	for (int i = 0; i < n; i++){
		while(x >= 0 && q[i] != p[x + 1]){
			x = fail[x];
		}
		if(q[i] == p[x + 1]){
			x++;
			if(x == m - 1){
				printf("%d\n", i - m + 2);
				return ;
			}
		}
	}
	printf("-1\n");
}

int main()
{
	//freopen("in.txt", "r", stdin);
	//freopen("out.txt", "w", stdout);

	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]);
		}
		getfail(b);
		/*for (int i = 0; i < m; i++){
			printf("%d ", fail[i]);
		}*/
		KMP(a, b);
	}

	return 0;
}
/**/

 

全部评论

相关推荐

11-28 17:48
中山大学 C++
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务