#include <bits/stdc++.h>
usingnamespace std;
int main()
{
int t; longlongint n, l;
int d;
cin >> t;
while(t--){
cin >> n >> d;
stringstream ss;
ss << n;
string s1=ss.str(); //converting n to string
int l1 = s1.length(); vector<int>c; char a[l1];
stringstream s;
s << d;
string s2=s.str(); //converting d to string
vector<char> v(s1.begin(), s1.end()); //converting string of n to a vector of char
char sml = *min_element(v.begin(), v.end()); //smallest number in vector
int min_pos = distance(v.begin(),min_element(v.begin(),v.end())); //position of smallest no
int k = 0;
//this condition checks if d is smaller than the smallest no of vector, if yes then the answer is d
if(d+'0' < sml){
int p = d;
for(longint i = 0; i < l1; i++)
cout << p;
cout << endl;
}
else{
for(int i = min_pos; i < l1; i++){
if(v[i] >= sml && v[i] <= d+'0'){
c.push_back(v[i]-'0');
}
} //all digits starting from smallest digit is checked if it is >= or <= to d. if yes then it is put in the final vector
int si = c.size();
for(int i = si; i < l1; i++){
c.push_back(d);
} //this is to fill the remaining places with d
k=0;
while(si--){
if(c[k+1] < c[k]){
c.erase(c.begin() + k);
c.push_back(d);
} //this is to make sure all digits are sorted. if not then it is removed and a d is inserted
else k++;
if(k >= c.size()-1)
break;
}
for(int i = 0; i < c.size(); i++){
cout << c[i];
}
cout << endl;
}
}
}
that's because you are invoking undefined behaviour by accessing `c' out of bounds. if(c[k+1] < c[k])
there was only one digit, but you are trying to access c[1] that doesn't exist
> this is to make sure all digits are sorted
bubble sort in just one pass... doesn't seem likely