【HDU 1711 Number Sequence】

Time Limit: 10000/5000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 30893    Accepted Submission(s): 12981

Problem Description

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.

Input

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].

Output

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

Sample Input

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

Sample Output

6 -1

Source

HDU 2007-Spring Programming Contest

Recommend

lcy

 

题解:

      ①KMP入门吧。

      ②贴一个板子,以前总是不熟练(打自己一下,啊!)。

#include<stdio.h>
#define go(i,a,b) for(int i=a;i<=b;i++)
int n,m,f[10003],j,C,T[1000004],P[10003];
int main()
{
	scanf("%d",&C);
	while(C--&&scanf("%d%d",&n,&m))
	{
		go(i,0,n-1)scanf("%d",T+i);
		go(i,0,m-1)scanf("%d",P+i);f[0]=f[1]=0;	
		go(i,1,m-1){j=f[i];while(j&&P[i]!=P[j])j=f[j];f[i+1]=P[i]==P[j]?j+1:0;}j=0;
		go(i,0,n-1){while(j&&P[j]!=T[i])j=f[j];j+=P[j]==T[i];
			    if(j==m){printf("%d\n",i-j+2);goto _;}}puts("-1");_:;
	}
	return 0;
}//Paul_Guderian

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Birds don't just fly they fall down and get up,
Nobody learns without getting it won.——————<Zootopia>

posted @ 2017-10-10 21:53  小米狐  阅读(180)  评论(0编辑  收藏  举报
TOP