Number Sequence (KMP的应用)

个人心得:朴素代码绝对超时,所以要用到KMP算法,特意了解了,还是比较抽象,要多体会

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+M1K+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<stdio.h>
 2 #include<string.h>
 3 #include<iostream>
 4 #include<algorithm>
 5 #include<utility>
 6 #include<queue>
 7 #include<set>
 8 using namespace std;
 9 int n,m;
10 int a[1000005],b[10005];
11 void getnext(int x[],int next[])
12 {
13     int i=0;
14     int j=-1;
15     next[i]=-1;
16     while(i<m)
17     {
18         if(j==-1||x[i]==x[j])
19         {
20             i++;
21             j++;
22             next[i]=j;
23         }
24         else
25             j=next[j];
26     }
27 }
28 int main()
29 {
30      int t;
31      scanf("%d",&t);
32      while(t--)
33      {
34          int next[10005];
35          int flag=-1;
36          scanf("%d%d",&n,&m);
37          for(int i=1;i<=n;i++)
38             scanf("%d",&a[i]);
39          for(int i=0;i<m;i++)
40             scanf("%d",&b[i]);
41         getnext(b,next);
42         int i=1,j=0;
43           while(i<=n&&j<m)
44           {
45               if(j==-1||a[i]==b[j])
46               {
47                   i++;
48                   j++;
49               }
50               else
51                 j=next[j];
52           }
53           if(j==m)  flag=i-j;
54           cout<<flag<<endl;
55 
56 
57      }
58     return 0;
59 
60 
61 }


原文地址:https://www.cnblogs.com/blvt/p/7270543.html