HDU 1711 (裸KMP) Number Sequence

题意:

用第二个数列去匹配第一个数列,输出第一次匹配到的位置,如果没有则输出-1.

分析:

这明显是一道裸的KMP。

我是在这篇博客上学的KMP算法的,讲得比较透彻。

http://blog.csdn.net/v_july_v/article/details/7041827

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstring>
 4 using namespace std;
 5 
 6 const int maxn1 = 1000000 + 10;
 7 const int maxn2 = 10000 + 10;
 8 int a[maxn1], b[maxn2], next[maxn2];
 9 int n, m;
10 
11 void get_next()
12 {
13     next[0] = -1;
14     int k = -1;
15     int j = 0;
16     while(j < m - 1)
17     {
18         if(k == -1 || b[j] == b[k])
19         {
20             k++;
21             j++;
22             next[j] = k;
23         }
24         else k = next[k];
25     }
26 }
27 
28 int KMP()
29 {
30     int i = 0, j = 0;
31     while(i < n && j < m)
32     {
33         if(j == -1 || a[i] == b[j])
34         {
35             i++;
36             j++;
37         }
38         else j = next[j];
39     }
40     if(j == m)  return i - j;
41     return -2;
42 }
43 
44 int main()
45 {
46     //freopen("in.txt", "r", stdin);
47     int T;
48     scanf("%d", &T);
49     while(T--)
50     {
51         memset(next, 0, sizeof(next));
52 
53         scanf("%d%d", &n, &m);
54         for(int i = 0; i < n; ++i)  scanf("%d", &a[i]);
55         for(int i = 0; i < m; ++i)  scanf("%d", &b[i]);
56         get_next();
57         printf("%d
", KMP()+1);
58     }
59 
60     return 0;
61 }
代码君
原文地址:https://www.cnblogs.com/AOQNRMGYXLMV/p/4109652.html