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 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
| struct Shash{ const i64 base[2] = {29, 31}; const i64 hashmod[2] = {(i64)1e9, 998244353};
std::array<std::vector<i64>, 2> hsh, pwMod; void init(std::string &s) { int n = s.size(); s = ' ' + s; hsh[0].resize(n + 1), hsh[1].resize(n + 1); pwMod[0].resize(n + 1), pwMod[1].resize(n + 1); for(int i = 0; i < 2; i++){ pwMod[i][0] = 1; for(int j = 1; j <= n; j++){ pwMod[i][j] = pwMod[i][j - 1] * base[i] % hashmod[i]; hsh[i][j] = (hsh[i][j - 1] * base[i] + s[j]) % hashmod[i]; } } } std::pair<i64, i64> get(int l, int r) { std::pair<i64, i64> ans; ans.first = (hsh[0][r] - hsh[0][l - 1] * pwMod[0][r - l + 1]) % hashmod[0]; ans.second = (hsh[1][r] - hsh[1][l - 1] * pwMod[1][r - l + 1]) % hashmod[1]; ans.first = (ans.first + hashmod[0]) % hashmod[0]; ans.second = (ans.second + hashmod[1]) % hashmod[1]; return ans; } bool same(int la, int ra, int lb, int rb){ return get(la, ra) == get(lb, rb); } };
signed main() { std::ios::sync_with_stdio(false); std::cin.tie(nullptr); int N, M; std::cin >> N >> M;
std::string S, T, s, t; std::cin >> S >> T;
s = std::string(S.rbegin(), S.rend()); t = std::string(T.rbegin(), T.rend());
Shash a, b, c, d; a.init(S), b.init(T); c.init(s), d.init(t);
int mn = std::min(N, M); std::vector<int> p(N + 1), n(M + 1);
for (int i = 1; i <= mn; i++) { auto l1 = a.get(1, i); auto l2 = c.get(N - i + 1, N); auto r1 = d.get(1, i); if (l1 == l2 && r1 == l1) p[i] = i; p[i] = std::max(p[i], p[i - 1]); }
for (int i = 1; i <= mn; i++) { auto l1 = b.get(1, i); auto l2 = d.get(M - i + 1, M); auto r1 = c.get(1, i); if (l1 == l2 && r1 == l1) n[i] = i; n[i] = std::max(n[i], n[i - 1]); }
int ans = -1; if (N <= M) { for (int i = 1; i <= N; i++) { if (p[i] && n[N - i]) { ans = std::max(ans, 2 * (p[i] + n[N - i])); } } } else { for (int i = 1; i <= M; i++) { if (p[M - i] && n[i]) { ans = std::max(ans, 2 * (n[i] + p[M - i])); } } } std::cout << ans << "\n";
return 0; }
|