Pasha 有一个正整数 a,不含前导 0 。今天,他认为这个数太小,希望把它变得更大一些。不幸的是,Pasha 只能交换这个整数的两个相邻的十进制数字。
请帮助 Pasha 计算出,他在不超过 k 次交换的条件下,能够取得的最大数是多少。
输入
输入一行,包含两个整数 a 和 k (1 ≤ a ≤ 10^18; 0 ≤ k ≤ 100)。
输出
打印 Pasha 在执行不超过 k 次交换的情况下,所能得到的最大数。
示例
输入
1990 1
输出
9190
输入
300 0
输出
300
输入
1034 2
输出
3104
输入
9090000078001234 6
输出
9907000008001234
纯暴力,利用swap交换
#include<stdio.h>
#include<assert.h>
#include<string.h>
#include<string>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<vector>
#include<queue>
#include<functional>
#include<map>
#include<set>
using namespace std;
typedef long long ll;
const int maxn = 1e7 + 10;
char a[maxn];
int k;
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cin >> a >> k;
if (k == 0) {
cout << a << endl;
return 0;
}
int n = strlen(a);
int pos;
for (int i = 0; i < n - 1; i++) {
pos = i;
for (int j = i + 1; j < n&&j - i <= k; j++) {
if (a[j] > a[pos])
pos = j; //在k步范围内记录下最大数的位置
}
for (int j = pos; j > i; j--) {
swap(a[j], a[j - 1]);//把最大的数从后向前交换
}
k -= (pos - i);//减去步数
}
cout << a << endl;
return 0;
}
pos = i;
for (int j = i + 1; j < n&&j - i <= k; j++) {
if (a[j] > a[pos])
pos = j;
}
for (int j = pos; j > i; j--) {
swap(a[j], a[j - 1]);
}
k -= (pos - i);
}
cout << a << endl;
return 0;
}