Beautiful Now
Time Limit: 5000/2500 MS (Java/Others) Memory Limit: 262144/262144 K (Java/Others)
Total Submission(s): 1714 Accepted Submission(s): 645
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
Recommend
chendu | We have carefully selected several similar problems for you: 6361 6360 6359 6358 6357
题意:给你一个数字,将这个数字中的任何位数之间进行交换k次,输出交换k次后的最大值和最小值。
题解:在dfs中进行暴力,将每个答案进行对比取最大或最小输出。在网上看了下别人的代码。。。
数据:542111 3
#include<bits/stdc++.h>
using namespace std;
int n,ans,qu[20];
char st[20];
int get(char *nn){
int a = 0;
for(int i = 0 ; i < n ; i++){
a += (nn[i]-'0')*qu[n-i-1];
}
return a;
}
void dfs(int k){
ans = min(ans,get(st));
if(k==0){
return;
}
for(int i = 0 ; i < n ; i++){
char nm = st[i];
char nm2 = st[i];
for(int j = i+1 ; j < n ; j++){
nm = min(nm,st[j]);
if(st[j]!='0'){
nm2 = min(nm2,st[j]);
}
}
if(i==0){
nm = nm2;
}
if(nm==st[i]){
continue;
}
for(int j = i+1 ; j < n ; j++){
if(st[j]==nm){
swap(st[j],st[i]);
dfs(k-1);
swap(st[j],st[i]);
}
}
return;
}
}
void dfs2(int k){
ans = max(ans,get(st));
if(k==0){
return;
}
for(int i = 0 ; i < n ; i++){
char nm = st[i];
for(int j = i+1 ; j < n ; j++){
nm = max(nm,st[j]);
}
if(nm==st[i]){
continue;
}
for(int j = i+1 ; j < n ; j++){
if(nm==st[j]){
swap(st[j],st[i]);
dfs2(k-1);
swap(st[j],st[i]);
}
}
ans = max(ans,get(st));
return;
}
}
int main(){
int k;
qu[0]=1;
for(int i = 1 ; i < 10 ; i++){
qu[i] = qu[i-1]*10;
}
int T;
cin>>T;
while(T--){
scanf("%s %d",st,&k);
n = strlen(st);
int tmp = get(st);
ans = tmp;
dfs(min(k,9));
printf("%d ",ans);
ans = tmp;
dfs2(min(k,9));
printf("%d\n",ans);
}
}