HDU - 1711:Number Sequence

Number Sequence

来源:HDU

标签:字符串、字符串匹配、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 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.

输入

The first line of input is a number T which indicate the number of cases. Each case contains three lines. The first line is two numbers N and M (1 <= M <= 10000, 1 <= N <= 1000000). The second line contains N integers which indicate a[1], a[2], … , a[N]. The third line contains M integers which indicate b[1], b[2], … , b[M]. All integers are in the range of [-1000000, 1000000].

输出

For each test case, you should output one line which only contain K described above. If no such K exists, output -1 instead.

输入样例

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

解题思路

KMP算法的典型应用。

参考代码

#include
#include
#define MAXN 1000005
#define MAXM 10005

int A[MAXN];
int B[MAXM];
int n,m;

int next[MAXM];

void getNext(int *T){
	int i=0, j=-1;
	next[0]=-1;
	while(i<m-1){
		if(j==-1 || T[i]==T[j]){
			++i; ++j;
			next[i]= (T[i]==T[j]? next[j]: j);
		}
		else j=next[j];
	}
}

int index(int *S, int *T){
	int i=0, j=0;
	while(i<n && j<m){
		if(j==-1 || S[i]==T[j]) {
			++i; ++j;
		}
		else j=next[j];
	}
	if(j==m) return i-j+1;
	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]);
		}
		getNext(B);
		printf("%d\n",index(A, B));
	}
}

你可能感兴趣的:(【记录】算法题解)