hdu1711 Number Sequence

Number Sequence

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


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模板,直接模板即可。
ac代码:
 1 #include <stdio.h>
 2 
 3 int a[1000000+50];
 4 int b[10000+50];
 5 int next[10000+50];
 6 int Kmp(int lena,int lenb);
 7 void get_Next(int lenb);
 8 
 9 int main()
10 {
11     int t;
12     scanf("%d", &t);
13     while(t--)
14     {
15         int n, m;
16         scanf("%d%d", &n, &m);
17         for(int i=0;i<n;i++) scanf("%d", &a[i]);
18         for(int i=0;i<m;i++) scanf("%d", &b[i]);
19         get_Next(m);
20         printf("%d\n", Kmp(n, m));
21     }
22     return 0;
23 }
24 //KMP算法
25 int Kmp(int lena,int lenb)
26 {
27     int i=0,j=0;
28     while(i<lena&&j<lenb)
29     {
30         if(j==-1||a[i]==b[j])
31         {
32             i++;
33             j++;
34         }
35         else
36             j=next[j];
37     }
38     if(j==lenb)
39         return i-lenb+1;
40     else
41         return -1;
42 }
43 void get_Next(int lenb)
44 {
45     int i=0,j=-1;
46     next[0]=-1;
47     while(i<lenb-1)
48     {
49         if(j==-1||b[i]==b[j])
50         {
51             i++;
52             j++;
53             next[i]=j;
54         }
55         else
56             j=next[j];
57     }
58 }
View Code

 

 
 
posted @ 2018-08-09 16:27  sqdtss  阅读(89)  评论(0编辑  收藏  举报