1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
| #include <bits/stdc++.h> using namespace std; struct KMP { string s, t; vector<int> nxt; KMP(string s, string t) : s(s), t(t), nxt(t.size()+1) {} auto init() { int len = t.size(), i = 0, j = -1; nxt[0] = -1; while (i < len) { if (j == -1 || t[i] == t[j]) { i++, j++; nxt[i] = j; } else { j = nxt[j]; } } return nxt; } auto run() { int si = 0, ti = 0, slen = s.size(), tlen = t.size(); vector<int> res; while (si < slen && ti < tlen) { if (ti == -1 || s[si] == t[ti]) { si++, ti++; } else { ti = nxt[ti]; } if (ti == tlen) { res.push_back(si - tlen); ti = nxt[ti]; } } return res; } }; int main() { ios::sync_with_stdio(false); cin.tie(0); string s, t; cin >> s >> t; KMP kmp(s, t); auto nxt=kmp.init(); auto res=kmp.run(); for (auto &i : res) cout << i + 1 << "\n"; for (int i = 1; i < nxt.size(); i++) cout << nxt[i] << " "; return 0; }
|