HDU 1711 Number Sequence

结题思路:KMP标准模板题,注意KMP有两个版本,这里的优劣在代码中已体现

 1 #include <iostream>
 2 #include <cstring>
 3 #include <string>
 4 #include <algorithm>
 5 using namespace std;
 6 
 7 int a[1000100];
 8 int b[10100];
 9 int Len_a, Len_b;
10 int Next[10100]
11 ;
12 void GetNext()
13 {
14     int i = 0, j = Next[0] = -1;
15     while (i < Len_b)
16     {
17         //Version 1
18         if (j == -1 || b[i] == b[j])
19             Next[++i] = ++j;
20         /* 
21              
22             Version 2:
23             if (j == -1 || b[i] == b[j])
24             {
25                 i++;
26                 j++;
27                 Next[i] = (b[i] == b[j] ? Next[j] : j)
28             }
29             改进的 next[] 表与不改进的 next[] 表相比,计算 next[] 表本身的时间慢一点,但 KMP 匹配的时候跳转的平均长度稍大一点。
30 
31             构造后一个 next[] 表只用一次体现不出优势。如果一个模式串要与很多个字符串匹配, 改进的 next[] 构造时间微不足道,匹配的速度就体现出来了。
32         */
33         else
34             j = Next[j];
35     }
36 }
37 
38 int KMP()
39 {
40     int i = 0, j = 0;
41     GetNext();
42     while (i < Len_a && j < Len_b)
43     {
44         if (j == -1 || a[i] == b[j])
45         {
46             i++;
47             j++;
48         }
49         else
50             j = Next[j];
51     }
52     
53     if (j == Len_b)
54         return i - j + 1;
55     else
56         return -1;
57 }
58 
59 int main(void)
60 {
61     ios::sync_with_stdio(false);
62     
63     int cas;
64     cin >> cas;
65     while (cas--)
66     {
67         cin >> Len_a >> Len_b;
68         for (int i = 0; i < Len_a; ++i)
69             cin >> a[i];
70             
71         for (int j = 0; j < Len_b; ++j)
72             cin >> b[j];    
73             
74         cout << KMP() << endl;
75     }
76     
77     return 0;
78 }
View Code

猜你喜欢

转载自www.cnblogs.com/ducklu/p/8921726.html