首页 > 代码库 > Number Sequence HDU - 1711
Number Sequence HDU - 1711
Given two sequences of numbers : a11 , a22 , ...... , aNN , and b11 , b22 , ...... , bMM (1 <= M <= 10000, 1 <= N <= 1000000). Your task is to find a number K which make aKK = b11 , aK+1K+1 = b22 , ...... , aK+M?1K+M?1 = bMM . If there are 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 two numbers N and M (1 <= M <= 10000, 1 <= N <= 1000000). The second line contains N integers which indicate a11
, a22
, ...... , aNN
. The third line contains M integers which indicate b11
, b22
, ...... , bMM
. All integers are in the range of ?1000000,1000000?1000000,1000000
.
OutputFor 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
1 #include<iostream> 2 #include<cstring> 3 #include<string> 4 #include<cstdio> 5 using namespace std; 6 7 int nxt[1000005],s[1000005],p[10005]; 8 int T,n,m; 9 10 void getNext(){ 11 nxt[0]=-1; 12 for(int i=0;i<m;i++){ 13 int k=nxt[i]; 14 while(k!=-1&&p[i]!=p[k]) k=nxt[k]; 15 nxt[i+1]=k+1; 16 } 17 } 18 19 int kmp(){ 20 getNext(); 21 int i=0,j=0; 22 while(i<n&&j<m){ 23 while(j!=-1&&s[i]!=p[j]) j=nxt[j]; 24 ++i; 25 ++j; 26 } 27 if(j==m) return i-j+1; 28 return -1; 29 } 30 31 int main() 32 { scanf("%d",&T); 33 while(T--){ 34 scanf("%d%d",&n,&m); 35 for(int i=0;i<n;i++) scanf("%d",&s[i]); 36 for(int i=0;i<m;i++) scanf("%d",&p[i]); 37 int ans=kmp(); 38 printf("%d\n",ans); 39 } 40 return 0; 41 }
Number Sequence HDU - 1711