Number Sequence

Number Sequence

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


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
基础的kmp字符串匹配
 1 #include<iostream>
 2 #include<cstdio>
 3 #include<string>
 4 #include<cstring>
 5 using namespace std;
 6 
 7 int k[10010];
 8 int h[1000010];
 9 int NEXT[10010];
10 
11 void GetNext(int k[],int y,int NEXT[]){
12     int klen=y+1;
13     int i=0;
14     int j=-1;
15     NEXT[0]=-1;
16     while(i<klen){
17         if(j==-1||k[i]==k[j]){
18             ++i;
19             ++j;
20             NEXT[i]=j;
21         }else{
22             j=NEXT[j];
23         }
24     }
25 }
26 
27 int kmp_find(int h[],int k[],int x,int y,int NEXT[]){
28      GetNext(k,y,NEXT);
29     int i=0;
30     int j=0;
31     int hlen=x+1;
32     int klen=y+1;
33     while(i<hlen&&j<klen){
34         if(j==-1||h[i]==k[j]){
35             i++;j++;
36         }else{
37             j=NEXT[j];
38         }
39     }
40      if(j==klen){
41             return i-j+1;
42         }
43     return -1;
44 }
45 int main(){
46     int a;
47     scanf("%d",&a);
48     while(a--){
49         int n,m;
50         scanf("%d%d",&n,&m);
51         int x,y;
52         for(int i=0;i<n;i++){
53           scanf("%d",&h[i]);
54             x=i;
55         }
56         for(int i=0;i<m;i++){
57           scanf("%d",&k[i]);
58             y=i;
59         }
60 
61         int t=kmp_find(h,k,x,y,NEXT);
62         cout<<t<<endl;
63         memset(NEXT,0,sizeof(NEXT));
64         memset(h,0,sizeof(h));
65         memset(k,0,sizeof(k));
66     }
67 return 0;
68 }

 

posted @ 2017-09-22 15:05  #忘乎所以#  阅读(228)  评论(0编辑  收藏  举报