1. 程式人生 > >hdoj 1711 Number Sequence KMP模板題

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;
}