HDOJ Number Sequence 1711【KMP裸题】

Number Sequence

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


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   |   We have carefully selected several similar problems for you:   1358  3336  1686  3746  2222 

#include <stdio.h>
#include <string.h>
#include <algorithm>

using namespace std;

int T[1000100]; //字 符 串 数 组 
int P[10010]; //模 式 串 
int pre[10010]; //记录 模式串的 最长 前缀

/*寻 找 最 长 前 缀*/
void getnext(int plen)
{
	pre[0]=pre[1]=0;
	for(int i=1;i<plen;i++)
	{
		int k=pre[i];
		while(k&&P[i]!=P[k]) k=pre[k];  //递归查找前一个pre 
		pre[i+1] = P[i]==P[k]? k+1 : 0;   
	}
} 

int kmpsearch(int slen,int plen)
{
	getnext(plen);
	int k=0;
	for(int i=0;i<slen;i++)
	{
		while(k&&P[k]!=T[i]) k=pre[k];
		if(P[k]==T[i]) k++;
		if(k==plen) return i-k+1; //起始字符匹配点i-(k-1); 
	}
	return -1;
}
int main()
{
	int t;
	scanf("%d",&t);
	int a,b;
	while(t--)
	{
		scanf("%d%d",&a,&b);
		for(int i=0;i<a;i++)
		scanf("%d",&T[i]);
		for(int i=0;i<b;i++)
		scanf("%d",&P[i]);
		int ans=kmpsearch(a,b);
		if(ans==-1)printf("-1\n");
		else printf("%d\n",ans+1); //数组下标加1。 
	}
	return 0; 
}


你可能感兴趣的:(HDOJ Number Sequence 1711【KMP裸题】)