hdu_1711Number Sequence(kmp)

Number Sequence

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


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 //kmp
 2 #include<cstdio>
 3 #include<cstring>
 4 #include<algorithm>
 5 using namespace std;
 6 int a[1000005],b[10005];
 7 int Next[10005];
 8 int n,m;
 9 int kmp()
10 {
11     int i,j;
12     j = 0;
13     int tm = Next[0] = -1;
14     //ÇóNextÊý×é
15     while(j<m-1){
16         if(tm<0||b[j]==b[tm])
17             Next[++j] = ++tm;
18         else tm = Next[tm];
19     }
20     //Æ¥Åä
21     for( i = j = 0; i < n&&j < m; ){
22         if(j<0||a[i]==b[j])i++,j++;
23         else j = Next[j];
24     }
25     if(j<m) return -1;
26     return i-j;
27 }
28 int main()
29 {
30     int T;
31     scanf("%d",&T);
32     while(T--)
33     {
34         scanf("%d%d",&n,&m);
35         for(int i = 0; i< n; i++)
36             scanf("%d",&a[i]);
37         for(int i = 0; i < m; i++)
38             scanf("%d",&b[i]);
39         int ans = kmp();
40         if(ans!=-1)
41         printf("%d
",ans+1);
42         else puts("-1");
43     }
44     return 0;
45 }
 
原文地址:https://www.cnblogs.com/shanyr/p/5676403.html