Number Sequence
Time limit:10000/5000 MS (java/others) Memory limit:32768/32768 K (java/others)
Total submission (s): 15052 Accepted Submission (s): 6597
Problem Descriptiongiven-sequences of numbers:a[1], a[2], ..., a[n], and b[1], b[2], ..., b[m] (1 <= M &L t;= 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 is more than one K exist, output the smallest one.
Inputthe first line of input is a number T which indicate the number of cases. Each case contains three lines. The first line is the 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 is in the range of [-1000000, 1000000].
Outputfor Each test case, you should the output one line which only contain K described above. If No such K exists, output-1 instead.
Sample Input213 51 2 1 2 3 1 2 3 1 3 2 1 21 2 3 1 313 51 2 1 2 3 1 2 3 1 3 2 1 21 2 3 2 1
Sample output6-1
Sourcehdu 2007-spring Programming Contest KMP Template title, returns the position of the first occurrence of the pattern string in the main string
#pragmaComment (linker, "/stack:1024000000,1024000000")#include<cstdio>#include<string>#include<iostream>#include<cstring>#include<cmath>#include<stack>#include<queue>#include<vector>#include<map>#include<stdlib.h>#include<algorithm>#defineLL __int64using namespacestd;Const intmaxn=1000000+5;intS[MAXN],T[MAXN];intNEX[MAXN];intn,m;voidKmp_nex () {intj,k; J=0; k=-1, nex[0]=-1; while(j<m) {if(k==-1|| t[j]==t[k]) nex[++j]=++K; Elsek=Nex[k]; }}intkmp_id () {intI=0, j=0; Kmp_nex (); while(I<n && j<m) {if(j==-1|| s[i]==T[j]) I++,j++; ElseJ=Nex[j]; } if(j==m)returni-m+1; Else return-1;}intMain () {//freopen ("In.txt", "R", stdin); intKase; scanf ("%d",&Kase); while(kase--) {scanf ("%d%d",&n,&m); for(intI=0; i<n;i++) scanf ("%d",&S[i]); for(intI=0; i<m;i++) scanf ("%d",&T[i]); printf ("%d\n", kmp_id ()); } return 0;}View Code
HDU 1711 KMP