Swap Digits CSU1270

Description

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

#include<cstdio>
#include<cstring>
#include<iostream>
using namespace std;
const int maxn = 1000+10;
char num[maxn];
int main() {
	int t, k;
	cin>>t;
	while(t--) {
			while (scanf("%d%s", &k,num) == 2) {
				int len = strlen(num);
				for (int i = 0; i < len; i++) {
					if (k <= 0) break;
					//找出num[i]后,k步内最大的数字
					char max = num[i];
					int id = i;
					for (int j = i + 1; j < len&&j <= i + k; j++) {
						if (max < num[j]) {
							max = num[j];
							id = j;
						}
					}
					//调整位置
					for (int j = id; j > i; j--) {
						num[j] = num[j - 1];
					}
					num[i] = max;
					k -= id - i;
				}
				printf("%s\n", num);
		}
	}
	return 0;
}


猜你喜欢

转载自blog.csdn.net/adusts/article/details/80540761