1270: Swap Digits
Time Limit: 1 Sec Memory Limit: 128 Mb Submitted: 652 Solved: 236Description
Now we have a number, you can swap any two adjacent digits of it, but you can not swap more than K times. Then, what is the largest probable number that we can get after your swapping?
Input
There is an integer T (1 <= T <= 200) in the first line, means there are T test cases in total.
For each test case, there is an integer K (0 <= K < 106) in the first line, which has the same meaning as above. And the number is in the next line. It has at most 1000 digits, and will not start with 0.
There are at most 10 test cases that satisfy the number of digits is larger than 100.
Output
For each test case, you should print the largest probable number that we can get after your swapping.
Sample Input
3 2 1234 4 1234 1 4321
Sample Output
3124 4213 4321
题目大意是给你一个数,每次可以交换相邻的两个数,问最多进行K次交换之后能得到的最大的数是多少。不交换或者不交换那么多次也是可以的。
解题思路是用字符数组接受这个数,从0号到K号找最大的元素(因为每次都只能交换相邻的两个数,所以最多可以将第K的位置的数交换到第一个),将它放到0号位置,从0到最大的那个数依次后移(就是模拟将0到K号位置内最大元素交换到0号位置的过程),假设在L位置,则将L号位置交换到0号需要L步,K自减L。然后从1号位置开始,重复上述步骤。最后得到的就是最大数了。下面看代码,不懂再问吧
#include<iostream>
#include<string>
#include<cstring>
using namespace std;
int main()
{
int t;
string str;
scanf("%d",&t);
while (t--)
{
int k;
scanf ("%d",&k);
cin >> str;
for (int i = 0; i < str.size(); i++)
{
char ma = '0';
int w = 0;
for (int j = i; j < str.size() && j <= i + k; j++)
{
if (str[j] > ma)
{
ma = str[j];
w = j;
}
}
if (ma > str[i])
{
for (int j = w; j > i; j--)
{
str[j] = str[j - 1];
}
str[i] = ma;
k -= w - i;
}
}
cout << str << endl;
}
return 0;
}