Swap Digits

本文介绍了一个算法问题,即如何通过有限次相邻数字交换得到最大可能的整数。该问题适用于最多1000位的数字,并限制了交换次数。文章提供了一种贪心算法的解决方案,通过将高位尽可能置为较大数值的方式逐步构建最大数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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<iostream>
#include<string.h>
using namespace std;

int main()
{
	int T, s, len;
	char ch[1001];
	cin >> T;	
	while(T--)
	{
		cin >> s >> ch;
		len = strlen(ch);
		for (int i = 0; i < len; i++)
		{
			if (s <= 0)break;
			char max = '0';
			int key;
			for (int j = i + 1; j < len && j <= i + s; j++){
				if (max < ch[j]){
					max = ch[j];
					key = j;
				}
			}
			if (max > ch[i])
			{
				for (int j = key; j > i; j--){
					ch[j] = ch[j - 1];
				}
				ch[i] = max, s -= key - i;
			}
		}
		cout << ch << endl;
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值