CF915C 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

题意:给你两个小于10^18的数a,b,a的每一位的数可以随意排列,求所得到的小于b的最大a
分析:每次暴力判断每一位数放前面时后面取最大是否大于b,如果不大于则当前位取这个数是最佳
AC代码:
#include <map>
#include <set>
#include <stack>
#include <cmath>
#include <queue>
#include <cstdio>
#include <vector>
#include <string>
#include <bitset>
#include <cstring>
#include <iomanip>
#include <iostream>
#include <algorithm>
#include <bits/stdc++.h>
#define ls (r<<1)
#define rs (r<<1|1)
#define debug(a) cout << #a << " " << a << endl
using namespace std;
typedef long long ll;
const ll maxn = 1e4+10;
const ll mod = 1000000007;
const double pi = acos(-1.0);
const double eps = 1e-8;
bool cmp( char p, char q ) {
    return p > q;
}
int main() {
    ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
    string s1, s2;
    while( cin >> s1 >> s2 ) {
        ll len1 = s1.length(), len2 = s2.length();
        sort(s1.begin(),s1.end());
        if( len1 < len2 ) {
            reverse(s1.begin(),s1.end());
            cout << s1 << endl;
            continue;
        }
        for( ll i = 0; i < len1; i ++ ) {
            for( ll j = len1-1; j > i; j -- ) {
                string t = s1;
                swap(s1[i],s1[j]);
                sort(s1.begin()+i+1,s1.end());
                if( s1 > s2 ) {
                    s1 = t;   //每次循环确定一个当前所能取到的最小值中的最大值数字
                } else {
                    break;
                }
            }
            //debug(s1);
        }
        cout << s1 << endl;
    }
    return 0;
}

  

转载于:https://www.cnblogs.com/l609929321/p/9720806.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值