KMP && ACA

KMP:

吼哇!

反正网上教程满天飞,我就不写了。

发个自己写的模板

 1  /**
 2     freopen("in.in", "r", stdin);
 3     freopen("right.out", "w", stdout);
 4 */
 5 //// /////////////////////////////
 6 #include <cstdio>
 7 #include <string>
 8 #include <iostream>
 9 using std::string;
10 const int N = 1000010;
11 
12 int nex[N];
13 
14 int main() {
15     freopen("in.in", "r", stdin);
16     freopen("right.out", "w", stdout);
17     string s, p;
18     std::cin >> s >> p;
19 
20     nex[0] = 0;
21     for(int i = 1, j = 0; i < p.size(); i++) {
22         while(j && p[i] != p[j]) {
23             j = nex[j - 1];
24         }
25         if(p[i] == p[j]) j++;
26 
27         /// while(j && p[i + 1] == p[j]) j = nex[j - 1];
28         /// 十分失败的优化,反例:
29         /// acccc
30         /// ccc
31         /// 001  :next
32         /// 可以看出能匹配两个串,但是这个优化只能算出一个来
33 
34         nex[i] = j;
35     }
36 
37     for(int i = 0, j = 0; i < s.size(); i++) {
38         while(j && s[i] != p[j]) {
39             j = nex[j - 1];
40         }
41         if(s[i] == p[j]) j++;
42         if(j == p.size()) {
43             printf("%d\n", i - j + 2);
44             j = nex[j - 1];
45         }
46     }
47 
48     for(int i = 0; i < p.size(); i++) {
49         printf("%d ", nex[i]);
50     }
51 
52     return 0;
53 }
KMP模板 洛谷P3375

相关文章:

  • 2021-10-22
  • 2021-06-18
  • 2021-09-21
  • 2021-12-27
  • 2022-12-23
  • 2021-07-20
  • 2021-11-22
  • 2021-10-03
猜你喜欢
  • 2022-01-20
  • 2022-01-04
  • 2022-12-23
  • 2022-02-21
  • 2022-12-23
  • 2021-12-20
  • 2022-12-23
相关资源
相似解决方案