C. 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

Output

4940

题意:

给你2串数字a,b 然后要你重组数字串a 令它在小于串b的前提下尽可能大

思路:

很明显有一种穷举法,利用STL里面的next_permutation可实现,但复杂度为18!,不现实,所以我们可以换一种思路,关键词有什么?尽可能大,小于b,我们还是可以枚举,但是换了一种方式,首先如果串a的长度是小于b的,很明显我们只要排一下序,然后再倒一下,就是答案了,如果长度相等的时候,我们可以这样来做,首先给a串排个序,然后我们来枚举每个i位置的数,要从大到小来枚举,然后再给i+1到后面排一个序,这是为什么呢?因为我们答案要尽可能大,所以如果每一个位置尽可能大,必然是符合提示的,然后排序后如果是小于b的可以继续下一个位置,如果>b,就说明在这个数在这个位置并且是最小的情况下并不符合条件,自然要换一个数.

code:

#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<vector>
#include<queue>
#include<string>
#include<string.h>
#include<set>
#include<stdlib.h>
#define INF 0x3f3f3f
using namespace std;
int main()
{
    string a, b, c;
    cin >> a >> b;
    sort(a.begin(), a.end());
    reverse(a.begin(), a.end());
    if (a.length() < b.length())
        cout << a << endl;
    else
    {
        reverse(a.begin(), a.end());
        for (int i = 0; i < a.length(); i++)
        {
            c = a;
            for (int j = a.length() - 1; j >= i; j--)
            {
                char temp = a[i];
                a[i] = a[j];
                a[j] = temp;
                sort(a.begin() + i + 1, a.end());
                if (a > b)
                {
                    a = c;
                }
                else
                    break;
            }
        }
        cout << a << endl;
    }
    return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值