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 }