Source Code
#include <bits/stdc++.h>
#define ll long long
#define pb push_back
#define TEST int t;cin>>t;while(t--)
#define rep(i,n) for(int i=0;i<n;i++)
#define fr first
#define sc second
#define popcount __builtin_popcountll
#define IOS ios_base::sync_with_stdio(false),cin.tie(0),cout.tie(0);
using namespace std;
const ll mod=1000000007;
typedef vector<int,int> p1;
typedef vector<ll,ll> p2;

int main()
{
    IOS;
    //TEST{

 string a,b,res="-1";
 cin>>a>>b;
string str[5005],sb[5005],st[5005],sbb[5005];

 rep(i,a.length()-1){
 string str1=a.substr(0,i+1);
 str[i]=str1;
 string str2=a.substr(i+1,a.length());
st[i]=str2;
 }
 rep(i,b.length()-1){
  string sb1=b.substr(b.length()-i-1,b.length());
 sb[i]=sb1;
  string sb2=b.substr(0,b.length()-i-1);
 sbb[i]=sb2;
 }
 bool l=0;
 rep(i,a.length()-1){
     if(l)break;
 for(int  j=0;j<b.length()-1;j++){
     if(string(sb[j]+st[i])==string(sbb[j]+str[i])){res=sbb[j]+str[i]; l=1;}
 }
 }
  if(a==b)res=a;
 cout<<res;
cout<<endl;
//}
    return 0;
}
Copy
Right into Two AlCoach
GNU G++17
1102 ms
50.8 MB
Time Limit Exceeded