Pasha Maximizes
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output
Pasha has a positive integer a without leading zeroes. Today he decided that the number is too small and he should make it larger. Unfortunately, the only operation Pasha can do is to swap two adjacent decimal digits of the integer.
Help Pasha count the maximum number he can get if he has the time to make at most k swaps.
Input
The single line contains two integers a and k (1 ≤ a ≤ 1018; 0 ≤ k ≤ 100).
Output
Print the maximum number that Pasha can get if he makes at most k swaps.
Sample test(s)
input
1990 1
output
9190
input
300 0
output
300
input
1034 2
output
3104
input
9090000078001234 6
output
9907000008001234
这道题主要考察的是问题的分析,可能有人会考虑用bfs去做,事实上这样做是错误的,要么你的界限是错的,要么不能得到最优解。仔细分析不难发现其实在k这个范围内的最大数越靠前,所得的值一定是该阶段下的最优解,利用这个去做,就A了。
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
char a[20];
int c[20];
int k,m;
int main()
{
while(scanf("%s%d",a,&k)!=EOF){
long long S=0;int K=0;
m=strlen(a);
for(int i=0;i<m;i++)
c[i]=a[i]-'0';
int N=0;
while(k>0&&N<m){
int Max=N,M=N+1;
while(M<m){
if(M>N+k) break;
if(c[M]>c[Max])
Max=M;
M++;
}
if(Max!=N){
for(int i=Max;i>N;i--){
int t;t=c[i];c[i]=c[i-1];c[i-1]=t;
}
k-=Max-N;
}
N++;
}
for(int i=0;i<m;i++)
printf("%d",c[i]);
printf("\n");
}
return 0;
}