hdu 1711

                                    Number Sequence

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

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<cmath>
 4 #include<cstring>
 5 #include<algorithm>
 6 #include<queue>
 7 #include<map>
 8 #include<set>
 9 #include<vector>
10 #include<cstdlib>
11 #include<string>
12 #define eps 0.000000001
13 typedef long long ll;
14 typedef unsigned long long LL;
15 using namespace std;
16 const int N=1000000+100;
17 int a[N],b[N];
18 int m,n;
19 void get_next(int T[],int next[]){
20     int j=0,k=-1;
21     next[0]=-1;
22     while(j<n){
23         if(k==-1||T[j]==T[k]){
24             j++;
25             k++;
26             next[j]=k;
27             //cout<<k<<" ";
28         }
29         else
30             k=next[k];
31     }
32 }
33 void  kmp(int S[],int T[]){
34     int i=0,j=0;
35     int next[100000];
36     get_next(T,next);
37     while(i<m){
38         if(j==-1||S[i]==T[j]){
39             i++;
40             j++;
41         }
42         else
43             j=next[j];
44         if(j==n){
45             printf("%d
",i-n+1);
46             return;
47         }
48     }
49     printf("-1
");
50 }
51 int main(){
52     int t;
53     scanf("%d",&t);
54     while(t--){
55         scanf("%d%d",&m,&n);
56         int x,y;
57         for(int i=0;i<m;i++){
58             scanf("%d",&a[i]);
59         }
60         for(int i=0;i<n;i++){
61             scanf("%d",&b[i]);
62         }
63         //get_next(b);
64         kmp(a,b);
65     }
66 }
原文地址:https://www.cnblogs.com/Aa1039510121/p/6361534.html