hdoj 1711 Number Sequence KMP模板题

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1711

    题目source:hdoj 1711 Number Sequence KMP分类难度级别1
	题目含义:两个数字串,寻找第二个数字串和第一个串中数字
匹配时候第一次出现的数字位置 
	解题思路:标准的KMP算法

#include<stdio.h>
int nextval[10100],b[10100],a[1000010];
int N,M;
void get_nextval(){
	int i=1;
	nextval[0]=0;
	int j=0;
	while(i<M){
		if(j==0||b[i]==b[j]){
			++i;++j;
			if(b[i]!=b[j])
				nextval[i]=j;
			else
				nextval[i]=nextval[j];
		}
		else
			j=nextval[j];
	}
}

int KMP(){
	get_nextval();
	int i=1,j=1;
	while(i<=N&&j<=M){
		if(j==0||a[i]==b[j]){
			++i;++j;
		}
		else
			j=nextval[j];
	}
	if(j>M) return i-M;
	else return -1;
}
int main(){
	int T;
	scanf("%d",&T);
	while(T--){
		scanf("%d %d",&N,&M);
		for(int i=1;i<=N;i++){
			scanf("%d",&a[i]);
		}
		for(int j=1;j<=M;j++){
			scanf("%d",&b[j]);
		}
		a[0]=b[0]=-1;
		printf("%d\n",KMP());
	} 
	return 0;
}

猜你喜欢

转载自blog.csdn.net/Dear_Jia/article/details/82179249