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
贪心题,在代码中解释。
AC代码如下:
大神代码:
9907000008001234
贪心题,在代码中解释。
AC代码如下:
#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
int main()
{
int k,t,i,j,l,temp;
char a[105];
int max,id;
cin>>a>>k;
l=strlen(a);
for(i=0;i<l;i++)//从高位开始往后找最大数
{
if(i==l-1)//到最后一位退出
break;
max=a[i];id=i;
t=k;
if(k>l-1-i)//if(k大于后面剩余的位数)
t=l-1-i;
for(j=i+1;j<=i+t;j++)
{
if(a[j]>max)
{
max=a[j];
id=j;
}
}
for(j=id;j>i;j--)//把最大数移到高位
{
temp=a[j];
a[j]=a[j-1];
a[j-1]=temp;
}
k-=(id-i);//k减去用去步数
}
cout<<a<<endl;
return 0;
}
大神代码:
#include <stdio.h>
#include <string>
#include <iostream>
#include <algorithm>
using namespace std;
#define long long long
#define f1(i,n) for (int i=1; i<=n; i++)
#define f0(i,n) for (int i=0; i<n; i++)
string a; int k;
bool maximize(char &a, char b)
{ if (a<b) a=b; else return false; return true; }
main(){
cin >> a >> k;
int n = a.size();
f0(i,n) {
char Max=a[i]; int Dec=i;
f0(j,k+1) if (i+j<n) if (maximize(Max, a[i+j])) Dec=i+j;
a.erase(Dec, 1);
a.insert(i, 1, Max);
k -= Dec-i;
}
cout << a << endl;
}