Now you are given one non-negative integer n in 10-base notation, it will only contain digits ('0'-'9'). You are allowed to choose 2 integers i and j, such that: i!=j, 1≤i<j≤|n|, here |n| means the length of n’s 10-base notation. Then we can swap n[i] and n[j].
For example, n=9012, we choose i=1, j=3, then we swap n[1] and n[3], then we get 1092, which is smaller than the original n.
Now you are allowed to operate at most M times, so what is the smallest number you can get after the operation(s)?
Please note that in this problem, leading zero is not allowed!
Input
The first line of the input contains an integer T (T≤100), indicating the number of test cases.
Then T cases, for any case, only 2 integers n and M (0≤n<10^1000, 0≤M≤100) in a single line.
3 9012 0 9012 1 9012 2Sample Output
9012 1092 1029
题意:给两个数字A,m,数字A的任意两位数字可以交换任意多次,求如果最多交换m次的最小数字
思路:数字要满足第一位不为0,且每次前面的较大的数字要和最后面的较小数字交换,才能保证此次交换使得数字为最小值
代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int N = 1005;
char str[N],s[N];
int m;
int main(){
int T;
scanf("%d",&T);
while(T--){
scanf("%s%d",str,&m);
int n=strlen(str);
strcpy(s,str);
sort(str,str+n);//最小数目标
if(str[0]=='0'){ //不能有前导0
for(int i=1;i<n;i++){
if(str[i]!='0'){
swap(str[0],str[i]);
break;
}
}
}
for(int i=0;i<n;i++){
if(m==0) break;
if(s[i]==str[i]) continue; //此位置为最优的
char tmp='9';
int x=-1;
for(int j=i+1;j<n;j++){ //找到最小的数字,及其位置
if(i==0&&s[j]=='0') continue;
if(s[j]<=tmp){
tmp=s[j];
x=j;
}
}
swap(s[i],s[x]);
m--;
}
printf("%s\n",s);
}
return 0;
}