#include<bits/stdc++.h> #define INF 0x3f3f3f3f #define maxn 10000010 typedeflonglong ll; usingnamespacestd; #define rep(i, n, args...) for (ll i = 0, ##args; i < n; i++) #define repr(i, s, e, args...) for (ll i = s, ##args; i < e; i++) #define erg(i, u, args...) for (ll i = vtx[u], ##args; ~i; i = eg[i].nxt) #define fulset(x, v) memset(x, v, sizeof(x)); /* 求解 T 中 next[],注释参考 GetExtend() */ voidGetNext(string & T, int & m, int next[]) { int a = 0, p = 0; next[0] = m; for (int i = 1; i < m; i++) { if (i >= p || i + next[i - a] >= p) { if (i >= p) p = i; while (p < m && T[p] == T[p - i]) p++; next[i] = p - i; a = i; } else next[i] = next[i - a]; } }
/* 求解 extend[] */ voidGetExtend(string & S, int & n, string & T, int & m, int extend[], int next[]) { int a = 0, p = 0; GetNext(T, m, next); for (int i = 0; i < n; i++) { if (i >= p || i + next[i - a] >= p) // i >= p 的作用:举个典型例子,S 和 T 无一字符相同 { if (i >= p) p = i; while (p < n && p - i < m && S[p] == T[p - i]) p++; extend[i] = p - i; a = i; } else extend[i] = next[i - a]; } }
intmain() { int next[100]; int extend[100]; string S, T; int n, m; while (cin >> S >> T) { n = S.size(); m = T.size(); GetExtend(S, n, T, m, extend, next); // 打印 next cout << "next: "; for (int i = 0; i < m; i++) cout << next[i] << " "; // 打印 extend cout << "\nextend: "; for (int i = 0; i < n; i++) cout << extend[i] << " "; cout << endl << endl; } return0; }