Description
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.
Output
Sample Input
Sample Output
题目大意:
在t组测试用例中,
给你一个数n 和 m,要求交换m次a[i]和a[j](i<j)得到的最小数,输出这个最小数
解题方法:
显然每次都是将最小的值移到前面去,那么我们用i记录已经确定了几个最小的值,
每确定一次就将最小值移到当前的下标,否则m++,继续找,
首位为0处理,用continue直接跳过;
扫描a[i],每次定位a[i],若此时a[i]不是最小的,如果a[i]<a[j]则交换一次值和下标; 若是最小的,m++,继续找;
而当i>=len,便不需要再交换了,直接输出最小
代码:
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> using namespace std; const int MAXN = 1000; int a[MAXN]; int t,n,m,cnt,minn; int main() { cin>>t; while(t--) { cnt=0; scanf("%d%d",&n,&m); memset(a,0,sizeof(a)); while(n) { a[cnt++]=n%10; n/=10; } for(int i=0; i<cnt/2; i++) swap(a[i],a[cnt-i-1]); ///重点从此次开始 for(int i=0; i<m; i++) { if(i>=cnt) break; minn=a[i]; int index=i; for(int j=i; j<cnt; j++) { if(a[j]==0&&i==0)///处理首位不为0 continue; if(minn>a[j]) { minn=a[j]; index=j; } } if(minn==a[i]) m++; else swap(a[i],a[index]); } for(int i=0; i<cnt; i++) printf("%d",a[i]); printf("\n"); } return 0; }
另附break与continue区别:
//break是结束整个循环体,continue是结束单次循环 比方说: while(x++ < 10) { if(x == 3) { break; } printf("%d\r\n", x); } 结果是输出 1 2 就退出了整个while循环 但是如果使用continue while(x++ < 10) { if(x == 3) { continue; } printf("%d\r\n", x); } 结果是:1 2 4 5 6 7 8 9 10 可见他仅仅是不输出3,因为他结束了本次循环