codeforces 915 C. Permute Digits【DFS + 离散化】

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/nobleman__/article/details/79055808

C. Permute Digits

time limit per test1 second
memory limit per test256 megabytes

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的最大值,保证有解

分析: 首先如果b的位数大于a的位数,那么答案就是a的字典序最大排列,如果恰好相等,可以dfs跑一边,每次选当前位数较大的数,如果最大的数当前位小于b,那么剩下的数可以从大到小排列,如样例 a = 4409 b = 5000,答案就是4940,相等的话继续搜下去,这里注意得回溯,考虑样例 a = 1230, b = 1300,第二位理论是放3较大,但是这里就不可以放,因为如果放了最后的数就会大于b,所以记得回溯,”还原现场”

#include<bits/stdc++.h>

using namespace std;

int vis[20];
int a2[22];
int len;
int res[22];
bool tag = false;

void dfs(int idx,bool flg) {
    if(tag) return ;
    if(idx == len) {
        tag = true;return;
    }
    int t;
    for(int i = 9;i >= 0;i--) {
        if(vis[i] > 0) {
            if(flg || i == a2[idx]) {
                vis[i]--;
                res[idx] = i;
                dfs(idx+1,flg);
                if(tag) return ;
                vis[i]++;
            } else if(i < a2[idx]) {
                vis[i]--;
                res[idx] = i;
                dfs(idx+1,true);
                if(tag) return ;
                vis[i]++;
            }
        }
    }
}

int main(){
    ios_base::sync_with_stdio(0);
    string s1,s2;cin>>s1>>s2;
    if(s1.size() < s2.size()) {
        sort(s1.rbegin(),s1.rend());
        cout<<s1<<endl;
    } else {
        len = s1.size();
        for(int i = 0;i < len;i++) {
            vis[s1[i] - '0']++;
        }

        for(int i = 0;i < len;i++) {
            a2[i] = s2[i] - '0';
        }
        dfs(0,false);
        for(int i = 0;i < len;i++) {
            cout<<res[i];
        }cout<<endl;
    }

    return 0;
}
  • 如有错误或遗漏,请私聊下UP,thx

没有更多推荐了,返回首页