Source Code
#include<bits/stdc++.h>
using namespace std;
#define ll long long

const int N = 1e5 + 5;

struct Hash {
	ll SEED = 26;
	ll MOD = 1000000007;
	ll SEED2 = 26;
	ll MOD2 = 1113;
	vector<ll> ha;
	vector<ll> ha2;
	vector<ll> power;
	vector<ll> power2;
	Hash(string x) {
		ha = vector<ll>(x.size());
		ha2 = vector<ll>(x.size());
		power = vector<ll>(x.size());
		power2 = vector<ll>(x.size());
		build(x);
	}
	void build(string x) {

	    for(int i=0; i<x.size() ; i++) x[i] -= 'a';
		power[0] = 1;
		power2[0] = 1;
		for(int i=1; i<(int)power.size(); i++) power[i] = (power[i-1] * SEED)%MOD;
		for(int i=1; i<(int)power2.size(); i++) power2[i] = (power2[i-1] * SEED2)%MOD2;
		ha[0] = x[0];
		ha2[0] = x[0];
		for(int i=1; i<(int)ha.size(); i++) ha[i] = (ha[i-1] * SEED + x[i])%MOD;
		for(int i=1; i<(int)ha2.size(); i++) ha2[i] = (ha2[i-1] * SEED2 + x[i])%MOD2;
	}
	//i,j inclusive
	pair<ll, ll> get(int i, int j) {
		ll ret = ha[j];
		if (i) ret -= ha[i-1] * power[j - i + 1] % MOD;
		ret = (ret % MOD + MOD) % MOD;
		ll ret2 = ha2[j];
		if (i) ret2 -= ha2[i-1] * power2[j - i + 1] % MOD2;
		ret2 = (ret2 % MOD2 + MOD2) % MOD2;
		return {ret,ret2};
	}
    pair<ll ,ll> cat(Hash a, int l, int r, Hash b, int l2, int r2)
	{
	    if(l > r)
            return b.get(l2,r2);
        if(l2 > r2)
            return a.get(l,r);

        pair<ll , ll> ha = a.get(l,r);
        pair<ll , ll> hb = b.get(l2,r2);

        ll ret = (hb.first + ((ha.first*power[r2-l2+1])%MOD))%MOD;
        ll ret2 = (hb.second + ((ha.second*power2[r2-l2+1])%MOD2))%MOD2;
        return {ret,ret2};
	}

};

int main()
{
    ios::sync_with_stdio(false);    cin.tie(NULL);  cout.tie(NULL);
    string a, b;
    cin >> a >> b;
    int len = a.length() + b.length();
    if(len%2 == 1)
    {
        cout << -1 << '\n';
        return 0;
    }

    Hash ha(a);
    Hash hb(b);
    len /= 2;
    bool ok = false;
    string res;

    for(int i = 0 ; i <= a.size() ; i++)
    {
        int curlen = (int)a.size() - i;
        if(curlen > len) continue;
        int j = len - curlen;

        pair<ll, ll> na = ha.cat(hb,b.length()-j,b.length()-1, ha,i,a.length()-1);
        pair<ll, ll> nb = ha.cat(hb,0,b.length()-j-1, ha,0,i-1);

        if(na.first == nb.first && na.second == nb.second)
        {
            ok = true;
            res = b.substr(b.length()-j) + a.substr(i);
            break;
        }
    }

    if(ok)
    {
        cout << res << '\n';
    }
    else
        cout << -1 << '\n';
}
Copy
Right into Two EsmaelSufe
GNU G++17
853 ms
1.6 MB
Accepted