Untitled
unknown
c_cpp
a year ago
1.9 kB
3
Indexable
Never
#include "bits/stdc++.h" using namespace std; #ifdef LOCAL #include "debug.h" #else #define debug(x...) #endif vector<int> z_function(string &s) { int n = s.size(); vector<int> z(n); for (int i = 1, l = 0, r = 0; i < n; i++) { z[i] = (r >= i ? min(z[i - l], r - i + 1) : 0); while (z[i] + i < n && s[z[i]] == s[z[i] + i]) { z[i]++; } if (r < z[i] + i - 1) { r = z[i] + i - 1; l = i; } } return z; } void solve() { string s, t; cin >> s >> t; int n1 = s.size(), n2 = t.size(); string g = s + "$" + t; string h = t + "$" + s; vector<int> z1 = z_function(g); vector<int> z2 = z_function(h); int best1 = INT_MAX, best2 = INT_MAX; for (int i = n1 + 1; i < n1 + n2 + 1; i++) { if (z1[i] == n1) { cout << t << '\n'; return; } if (z1[i] + i == n1 + n2 + 1) { best1 = i - n1 - 1; break; } } for (int i = n2 + 1; i < n1 + n2 + 1; i++) { if (z2[i] == n2) { cout << s << '\n'; return; } if (z2[i] + i == n1 + n2 + 1) { best2 = i - n2 - 1; break; } } if (best1 == INT_MAX && best2 == INT_MAX) { cout << s + t << '\n'; return; } if (n1 - best1 >= n2 - best2) { for (int i = 0; i < best1; i++) { cout << t[i]; } cout << s << '\n'; } else { for (int i = 0; i < best2; i++) { cout << s[i]; } cout << t << '\n'; } } signed main() { ios::sync_with_stdio(false); cin.tie(NULL); int tests = 1; cin >> tests; while (tests--) { solve(); } return 0; }