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
贪心问题
从最高位往下优先找k次翻动范围里面最大的数字放到最前面即可(不一定会消耗k步)
然后循环直到k走完或者数字已经最大了
#include <iostream>
#include <stdio.h>
using namespace std;
const int M=20;
int num[M];
int main()
{
long long a;
int k;
while(scanf("%I64d%d",&a,&k)!=EOF)
{
int p=0;
while(a>0)
{
num[p]=a%10;
p++;
a/=10;
}
//cout<<" "<<p;
int pp=p-1;
while(p>=0&&k>0)
{
while(p>=0&&k>0&&k>=p) //其实想想好像不分k与p(位数)的关系也可以,多写判断就好了
{
int maxn=0;
int pn=0;
for(int i=p-1;i>=0;i--)
{
if(num[i]>maxn)
{
maxn=num[i];
pn=i;
}
}
if(maxn==0)
{
p--;
continue;
}
//cout<<maxn<<" "<<pn<<endl;
for(int i=pn;i<=p-2;i++)
{
int t=num[i];
num[i]=num[i+1];
num[i+1]=t;
k--;
}
p--;
}
while(k>0&&k<p)
{
int maxn=0;
int pn=0;
for(int i=p-1;i>=p-1-k;i--)
{
if(num[i]>maxn)
{
maxn=num[i];
pn=i;
}
}
if(maxn==0)
{
p--;
continue;
}
//cout<<maxn<<" "<<pn<<" "<<k<<endl;
for(int i=pn;i<=p-2;i++)
{
int t=num[i];
num[i]=num[i+1];
num[i+1]=t;
k--;
}
p--;
}
}
for(int i=pp;i>=0;i--)
printf("%d",num[i]);
printf("\n");
}
return 0;
}