1. 程式人生 > >HDU - 1711 Number Sequence

HDU - 1711 Number Sequence

esc -- nbsp scan mes each describe for ase

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.
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 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].
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
將字符換成數字的KMP
 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 
 5 using namespace std;
 6 
 7 int s[10005],ss[1000005],Next[10005];
 8 int T,n,m;
 9 
10 void getnext(int* s)
11 { 12 Next[0]=0; 13 Next[1]=0; 14 for(int i=1;i<m;i++) 15 { 16 int j=Next[i]; 17 while(j&&s[i]!=s[j]) 18 j=Next[j]; 19 if(s[i]==s[j]) 20 Next[i+1]=j+1; 21 else 22 Next[i+1]=0; 23 } 24 } 25 26 int
main() 27 { 28 scanf("%d",&T); 29 while(T--) 30 { 31 int flag=0; 32 memset(Next,0,sizeof(Next)); 33 memset(ss,0,sizeof(ss)); 34 memset(s,0,sizeof(s)); 35 scanf("%d%d",&n,&m); 36 for(int i=0;i<n;i++) 37 scanf("%d",&ss[i]); 38 for(int i=0;i<m;i++) 39 scanf("%d",&s[i]); 40 getnext(s); 41 int j=0; 42 for(int i=0;i<n;i++) 43 { 44 while(j&&s[j]!=ss[i]) 45 j=Next[j]; 46 if(ss[i]==s[j]) 47 j++; 48 if(j==m) 49 { 50 flag=1; 51 printf("%d\n",i-m+2); 52 } 53 54 } 55 if(flag==0) 56 printf("-1\n"); 57 } 58 59 60 return 0; 61 }

HDU - 1711 Number Sequence