Beautiful Now
Time Limit: 5000/2500 MS (Java/Others) Memory Limit: 262144/262144 K (Java/Others)
Total Submission(s): 1055 Accepted Submission(s): 364
Problem Description
Anton has a positive integer n, however, it quite looks like a mess, so he wants to make it beautiful after k swaps of digits.
Let the decimal representation of n as (x1x2⋯xm)10 satisfying that 1≤x1≤9, 0≤xi≤9 (2≤i≤m), which means n=∑mi=1xi10m−i. In each swap, Anton can select two digits xi and xj (1≤i≤j≤m) and then swap them if the integer after this swap has no leading zero.
Could you please tell him the minimum integer and the maximum integer he can obtain after k swaps?
Input
The first line contains one integer T, indicating the number of test cases.
Each of the following T lines describes a test case and contains two space-separated integers n and k.
1≤T≤100, 1≤n,k≤109.
Output
For each test case, print in one line the minimum integer and the maximum integer which are separated by one space.
Sample Input
5
12 1
213 2
998244353 1
998244353 2
998244353 3
Sample Output
12 21
123 321
298944353 998544323
238944359 998544332
233944859 998544332
Source
2018 Multi-University Training Contest 5
#include<bits/stdc++.h>
using namespace std;
#define LL long long
#define clr(a) memset(a,0,sizeof(a))
const int MAXN = 1e5+10;
const int INF = 0x3f3f3f3f;
int T,k,len;
string s,str;
int maxx ,minn;
int change(string s){
int num = 0;
for(int i=0;i<s.size();i++){
num = num * 10 + (s[i]-'0');
}
return num;
}
void findmaxx(string s, int id, int k) {
maxx = max(maxx,change(s));
if(k == 0 || id == len) return ;
char t = s[id];
for(int j = id + 1; j < len; ++j)
t = max(t, s[j]);
if(t == s[id])
findmaxx(s, id + 1, k);
else {
for(int j = id + 1; j < len; ++j) {
if(s[j] == t) {
swap(s[id], s[j]);
findmaxx(s, id + 1, k - 1);
swap(s[id], s[j]);
}
}
}
}
void findminn(string s, int id, int k) {
minn = min(minn, change(s));
if(k == 0 || id == len) return ;
char t = s[id];
for(int j = id + 1; j < len; ++j)
t = min(t, (id == 0 && s[j] == '0' ? '9' : s[j]));
if(t == s[id])
findminn(s, id + 1, k);
else {
for(int j = id + 1; j < len; ++j) {
if(s[j] == t) {
swap(s[id], s[j]);
findminn(s, id + 1, k - 1);
swap(s[id], s[j]);
}
}
}
}
int main(){
scanf("%d",&T);
while(T--){
cin>>s>>k;
maxx = 0;minn = INF;
len = s.size();
str = s;
findmaxx(s,0,k);
findminn(s,0,k);
printf("%d %d\n",minn,maxx);
}
return 0;
}