Fork me on GitHub

HDU - 1711 Number Sequence

题目:

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 using namespace std;
 3 
 4 int N,M;
 5 
 6 //计算next数组
 7 int* get_next(int* b){
 8     int* next=new int[M];
 9     next[0]=-1;
10     int k=-1;
11     for(int q=1;q<M;q++){
12         while(k>-1&&b[k+1]!=b[q]){
13             k=next[k];
14         }
15         if(b[k+1]==b[q]){
16             k++;
17         }
18         next[q]=k;
19     }
20     return next;
21 }
22 
23 int main(){
24     int T=0;
25     cin >>T;
26     for(int i=0;i<T;i++){
27         cin >>N>>M;
28         int *a=new int[N];
29         int *b=new int[M];
30         for(int j=0;j<N;j++){
31             cin >>a[j];
32         }
33         for(int j=0;j<M;j++){
34             cin >>b[j];
35         }
36         //KMP
37         bool found=false;
38         int* next=get_next(b);
39         int k=-1;
40         for(int j=0;j<N;j++){
41             while(k>-1&&a[j]!=b[k+1]){
42                 k=next[k];
43             }
44             if(a[j]==b[k+1]){
45                 k++;
46             }
47             if(k==M-1){
48                 found=true;
49                 cout <<j-M+2<<endl;
50                 break;
51             }
52         }
53         if(!found){
54             cout <<-1<<endl;
55         }
56     }
57     system("pause");
58     return 0;
59 }

 

posted @ 2020-06-17 21:21  shiyu-coder  阅读(98)  评论(0)    收藏  举报