CodeForces-915C Permute Digits

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
output4940  题目链接

题意
给两个数a和b,可以任意调换a中数字的位置,问由a变成的最大的不超过b的数是什么?

分析

暴搜加剪枝。因为结果一定存在,那么可以分为两种情况,lena<lenb或是lena==lenb。当lena<lenb时,从大到小输出a中的数即可。
当lena==lenb时,我们尽量保持
和b的对应位相等,若一出现某位的数小于b上的数,剩下的数从大到小输出就好。
但是,会遇到前面都匹配的是相等的数,到了这一位,没有小于等于b对应位的数,这样构造出来的值就会大于b了,
这样子是不行的,所以我们得回溯,这样就需要dfs了。


#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstdlib>
#include<algorithm>
#include<cstring>
#include <queue>
#include <vector>
#include<bitset>
using namespace std;
typedef long long LL;
const int maxn = 400;
const int mod = 772002+233;
typedef pair<int,int> pii;
#define X first
#define Y second
#define pb push_back
//#define mp make_pair
#define ms(a,b) memset(a,b,sizeof(a))

const int inf = 0x3f3f3f3f;
char a[20],b[20],ans[20];
int cnt[10];
int lena,lenb;
bool dfs(int idx,int flag){
    if(idx==lenb) return true;

    for(int ia=9;ia>=0;ia--){
        if(cnt[ia]){
            if(flag ||ia+'0'==b[idx]){//此前b已比ans大了
                ans[idx]=ia+'0';
                cnt[ia]--;
                if(dfs(idx+1,flag)) return true;
                cnt[ia]++;
            }else if(ia+'0'<b[idx]){
                ans[idx]=ia+'0';
                cnt[ia]--;
                if(dfs(idx+1,flag|1))
                    return true;
            }
        }
    }
    return false;
}
int main(){
    scanf("%s%s",a,b);
    lena=strlen(a);
    lenb=strlen(b);

    if(lena<lenb){
        sort(a,a+lena);
        for(int i=lena-1;i>=0;i--) putchar(a[i]);
    }else{
        ms(cnt,0);
        for(int i=0;i<lena;i++) cnt[a[i]-'0']++;
        dfs(0,0);
        ans[lena]=0;
        puts(ans);
    }
}
 
    

 

 


转载于:https://www.cnblogs.com/fht-litost/p/8564757.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值