Source Code
#include "bits/stdc++.h"
using namespace std;
typedef long long ll; 
#define endl '\n';
#define mp make_pair
#define pb push_back

bool fun(string a){
    if(a==""){
        return 1;
    }
    if(a.size()%2){
        return 0;
    }
    int l=0,r=a.size()/2;
    while (r!=a.size()){
        if(a[r]!=a[l]){
            return 0;
        }
        // else aa+=a[l];
        l++;
        r++;
    }
    return 1;
}
void solve (){
    string a,b;
    cin>>a>>b;
    if(a==b){
        cout<<a;
        return;
    }
    int f=1,ff=1;
    for(int i=1;i<a.size();i++){
        if(a[i]!=a[i-1]){
            f=0;
            break;
            }
    }
    for (int i=1;i<b.size();i++){
        if(b[i]!=b[i-1]){
            ff=0;
            break;
        }
    }
    if(f &&ff &&a[0]==b[0] ){
        if((a.size()+b.size())%2==0){
        for (int i=0;i<(a.size()+b.size())/2;i++){
            cout<<a[0];
        }
        return;
        }
        else{
            cout<<-1;
            return;
        }
    }
    string aa="",bb="",ans="";
    if(fun(a)&& fun(b)){
       aa=a.substr(0,a.size()/2);
       bb=b.substr(0,b.size()/2);
       cout<<bb+aa;
       return;
    }
    for (int i=0;i<a.size();i++){
        for (int j=i;j<a.size();j++){ 
            if((b.find(a.substr(i,j-i+1)))!=string::npos){
                string at=a,bt=b;
                aa=at.erase(i,j-i+1);
                bb=bt.erase((b.find(a.substr(i,j-i+1))),j-i+1);
                // cout<<fun(aa);
                if(fun(aa) && fun(bb)){
                    if(bb!="")
                        ans+=bb.substr(0,bb.size()/2);
                    ans+=a.substr(i,j-i+1);
                     if(aa!="")
                        ans+=aa.substr(0,aa.size()/2);
                }
            }
        }
    }
    if(ans==""){
        cout<<-1;
        return;
    }
    cout<<ans;
}
int main ()
{    
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    //freopen ("input.txt","r",stdin);
    //freopen("output.txt","w",stdout);
    int t=1;
    //cin>>t;
    while (t--)
        solve();

    return 0;
}
Copy
Right into Two noomaL
GNU G++17
1100 ms
884 KB
Time Limit Exceeded