CF 435B Pasha Maximizes(249.B)

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

贪心题,在代码中解释。


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;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值