寻找最大数(三)
时间限制:
1000 ms | 内存限制:
65535 KB
难度:
2
-
描述
-
给出一个整数N,每次可以移动2个相邻数位上的数字,最多移动K次,得到一个新的整数。
求这个新的整数的最大值是多少。
-
输入
-
多组测试数据。
每组测试数据占一行,每行有两个数N和K (1 ≤ N≤ 10^18; 0 ≤ K ≤ 100).
输出
- 每组测试数据的输出占一行,输出移动后得到的新的整数的最大值。 样例输入
-
1990 1 100 0 9090000078001234 6
样例输出
-
9190 100 9907000008001234
#include <iostream>
#include <string>
using namespace std;
int main()
{
int n;
string str;
while(cin>>str>>n){
/**
example:23916 3
23916 > 92316(2) > 93216(1)
*/
int len = str.length();
for(int i = 0; i<len && n; i++){
int t = i;
for(int j = i+1; j<=i+n&&j<len;j++)
if(str[j]>str[t]) t = j;//搜索范围内最大数,存储pos
for(int y = t; y > i; y--)
swap(str[y],str[y-1]);//相邻两个数交换
n -= (t-i);//相邻两个数交换1次,交换(t-i)*1 ;更新可移动数
}
cout<<str<<endl;
}
return 0;
}
# 思路来源:https://blog.csdn.net/a2459956664/article/details/51557224
# 贪心,求解区间最优,考虑搬动的时间复杂度,好像样例的数据不大,搬动swap AC