1
0
Fork 0

Update include.hh

This commit is contained in:
Ariel 2024-01-18 12:36:04 +08:00 committed by GitHub
parent 490360c54e
commit d2207f6446
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
1 changed files with 18 additions and 20 deletions

View File

@ -97,17 +97,17 @@ template<typename T, typename... U> void __read(T& x, U&... args) { cin >> x; __
#define popfront(q, ...) __AS_PROCEDURE(auto [__VA_ARGS__] = q.front();q.pop_front();) #define popfront(q, ...) __AS_PROCEDURE(auto [__VA_ARGS__] = q.front();q.pop_front();)
/* algorithms */ /* algorithms */
vector<int> calc_next(string t) { // pi function of t vector<int> calc_next(string t) { // pi function of t
int m = t.length(); int n = (int)t.length();
vector<int> next; next.push_back(-1); vector<int> pi(n);
int j = -1, i = 0; for (int i = 1; i < n; i++) {
while (i < m) int j = pi[i - 1];
if (j == -1 || t[i] == t[j]) { while (j > 0 && t[i] != t[j]) j = pi[j - 1];
++i, ++j; if (t[i] == t[j]) j++;
if (i != m && t[i] == t[j]) next.push_back(next[j]); pi[i] = j;
else next.push_back(j); }
} else j = next[j]; return pi;
return next;
} }
vector<int> calc_z(string t) { // z function of t vector<int> calc_z(string t) { // z function of t
int m = t.length(); int m = t.length();
@ -127,15 +127,13 @@ vector<int> calc_z(string t) { // z function of t
return z; return z;
} }
vector<int> kmp(string s, string t) { // find all t in s vector<int> kmp(string s, string t) { // find all t in s
int n = s.length(), m = t.length(); string cur = t + '#' + s;
vector<int> next= calc_next(t); int sz1 = s.size(), sz2 = t.size();
vector<int> res; vector<int> v;
int i = 0, j = 0; vector<int> lps = calc_next(cur);
while (i < n && j < m) for (int i = sz2 + 1; i <= sz1 + sz2; i++) {
if (j == -1 || s[i] == t[j]) { if (lps[i] == sz2) v.push_back(i - 2 * sz2);
++i, ++j; }
if (j == m) res.push_back(i - j), j = next[j]; return v;
} else j = next[j];
return res;
} }
///////////////////////////////////////////////////////// /////////////////////////////////////////////////////////