cf Educational Codeforces Round 36 C. Permute Digits

原题:
You are given two positive integer numbers a and b. Permute (change order) of the digits of a to construct maximal number not exceeding b. No number in input and/or output can start with the digit 0.

It is allowed to leave a as it is.

Input
The first line contains integer a (1 ≤ a ≤ 1018). The second line contains integer b (1 ≤ b ≤ 1018). Numbers don’t have leading zeroes. It is guaranteed that answer exists.

Output
Print the maximum possible number that is a permutation of digits of a and is not greater than b. The answer can’t have any leading zeroes. It is guaranteed that the answer exists.

The number in the output should have exactly the same length as number a. It should be a permutation of digits of a.

Examples
input
123
222

output
213

input
3921
10000

output
9321

input
4940
5000
output
4940

中文:
给你两个数a和b,现在允许你将a中每位数字重新排列,使得从新排列得到的数在小于b的情况下最大。

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;

int num[10];
ll p[19];
char s[20], a[20];
ll aim, ans;
int flag = 0, len,fin=0;
int cmp(const char &c1,const char &c2)
{
    return c1>c2;
}

void dfs(int ind, ll tot)
{
    if (tot>aim)//当前的数比目标值大
        return;

    if (ind == len )//结束
    {
        ans = tot;
        fin = 1;
        return;
    }
    else
    {
        int tmp;
        if (!flag)
            tmp = a[ind] - '0';
        else
            tmp = 9;

        for (int i = tmp; i >= 0; i--)
        {
            if (num[i]>0)
            {
                if (i != a[ind] - '0')//如果出现当前位数比目标位数小
                    flag = 1;
                num[i]--;
                dfs(ind + 1, tot + i * p[len - ind - 1]);
                num[i]++;
                if (fin)
                    return;
            }
        }
    }

}


int main()
{
    ios::sync_with_stdio(false);
    while (cin >> s >> a)
    {
        if(strlen(a)>strlen(s))
        {
            sort(s,s+strlen(s),cmp);
            cout<<s<<endl;
            continue;
        }

        aim = stoll(a);
        len = strlen(a);
        memset(num, 0, sizeof(num));
        p[0] = 1;
        for (int i = 1; i <= 18; i++)
            p[i] = p[i - 1] * 10;
        for (int i = 0; i<strlen(s); i++)
            num[s[i] - '0']++;
        dfs(0, 0);
        cout << ans << endl;

    }


    return 0;
}

解答:

刚开始想的时候跑偏了,先从头枚举b中的每一位数,然后尽量找a中数字和b当中所枚举的数字相同的,不过这个想法是错的,例如
98
91
最后得到的结果应该89

考虑贪心的思想加上回溯的方法解决,依然从左到右枚举b中的数字,然后去a中寻找尽量和b当前所枚举到的数字相同的数位,如果发现后面的数字加上以后比b大,则回溯即可。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值