Educational Codeforces Round 36 C. Permute Digits DP

C. Permute Digits
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output

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小且尽可能大的数

思路:首先将a的所有数位找出并排序,然后从高位到低位,数字从大到小逐个尝试。选定某个数位后,将之后的数字组合为最小的组合,将新得到的数字a与b比较,若a<b,则说明该位的数字选取成功,反之则将该位选取较小的数字再次尝试。本题中,使用字符串会简单些。

用爆搜貌似也能过

代码如下:

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
bool cmp(char x,char y)
{
    return x>y;
}




int main()
{
    string a,b;
    while (cin>>a>>b){
        int alen=a.size();
        int blen=b.size();
        if (alen<blen){
            sort(a.begin(),a.end(),cmp);
            cout<<a<<endl;
            continue;
        }
        else{
            sort(a.begin(),a.end());
            string tmp;
            //对于每个数位从大数到小数逐个尝试是否可行,最后得到的一定是尽可能大的数
            for (int i=0;i<alen;i++){
                for (int j=alen-1;j>=0;j--){
                    tmp=a;
                    swap(a[i],a[j]);
                    sort(a.begin()+i+1,a.end());
                    if (a>b)
                        a=tmp;
                    else
                        break;
                }
            }
            cout<<a<<endl;
        }


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值