hdu 1711 Number Sequence

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1711

题目大意:在母链中找到子链的位置,输出开始的位置。

 1 #include <iostream>
 2 #include <cstdio>
 3 using namespace std;
 4 int lens,lenc,next[1000005],str[1000005],ch[1000005];
 5 
 6 int get_next()
 7 {
 8     int i=0,j=-1;
 9     next[0]=-1;
10     while (i<lens)
11     {
12         if (j==-1||str[i]==str[j])
13         {
14             i++;
15             j++;
16             next[i]=j;
17         }
18         else
19             j=next[j];
20     }
21 }
22 
23 int kmp()
24 {
25     int i=0,j=0;
26     get_next();
27     while (i<lenc)
28     {
29         if(j==-1||str[j]==ch[i])
30         {
31             i++;
32             j++;
33         }
34         else
35             j=next[j];
36         if (j==lens)
37             return i-j+1;
38 
39     }
40     return -1;
41 }
42 
43 int main ()
44 {
45     int t;
46     scanf("%d",&t);
47     while (t--)
48     {
49         //int n,m;
50         scanf("%d%d",&lenc,&lens);
51         for (int i=0; i<lenc; i++)
52             scanf("%d",&ch[i]);
53         for (int j=0; j<lens; j++)
54             scanf("%d",&str[j]);
55         printf ("%d
",kmp());
56     }
57     return 0;
58 }
原文地址:https://www.cnblogs.com/qq-star/p/3890560.html