Smallest KMP(want to know why my code is wrong.I have tried lots of test cases and i am getting right answers.)

#include<bits/stdc++.h>
using namespace std;
int main(){
int t;
cin>>t;
int j=0;
while(t!=0){
string s;
cin>>s;
string p;
cin>>p;

for(int i=0;i<s.size();i++){
if(p[j]==s[i]){
s.erase(i, 1);
i=-1;
j++;;
}

}
sort(s.begin(), s.end());
string flag;
flag=s;
for(int i=0;i<s.size();i++){
if(s[i]>p[0]){
s.insert(i, p);
break;
}
}
if(s!=flag){
cout<<s<<endl;
}

   else if(s==flag){
       if(s[s.size()-1]<p[0]){
           s.insert(s.size(),p);
           cout<<s<<endl;
        }
        else{
             for(int i=0;i<s.size();i++){
                if(s[i]==p[0]){
                   s.insert(i, p);
                     break;
                 }
            }
            cout<<s<<endl;
        }
    }
   j=0;
    t--;
}
return 0;

}

2
vvvvccccbbbaaa cab
aabbccccabvvvv
nnnnnaaaaajjjj jja
aaaajjjjannnnn

In above test cases your answer in 1st test case is: aabbccccabvvvv but the correct answer is: aabbcabcccvvvv as you can see “cab” is lexographically smaller than “ccc”.
Similarily for test case 2: jja is lexographically smaller than jjj.