Min Number
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
模拟
code:
#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
using namespace std;
char str[1005],s[1005];
int main(){
int T;
scanf("%d",&T);
while(T--){
int m;
scanf("%s%d",str,&m);
strcpy(s,str);//重新将str存一遍
int n = strlen(s);
sort(s,s+n);//给新的字符串从小到大排序
for(int i = 0; i < n; i++){
if(s[i] != '0'){//把前导零和最小的非零数交换,得到满足题意的最小数字
swap(s[i],s[0]);
break;
}
}
for(int i = 0; i < n; i++){
if(m == 0) break;
if(s[i] == str[i]) continue;//如果和最小情况数字相同就不需要换
char tmp = '9';
int x = i+1;
for(int j = i+1; j < n; j++){
if(i == 0 && str[j] == '0') continue;//如果前面位置是第一个位置并且后面位置数字是0不能换,因为换了会出现前导零
if(str[j] <= tmp){//找出最后面最小的数字
x = j;
tmp = str[j];
}
}
swap(str[i],str[x]);//交换
m--;
}
printf("%s\n",str);
}
return 0;
}
本文介绍了一个关于如何通过交换数字中的两个位来最小化一个非负整数的问题,并提供了一段C++代码实现。该问题的目标是在不超过指定次数的情况下找到最小可能的10进制表示形式,不允许出现前导零。
301

被折叠的 条评论
为什么被折叠?



