首页 > 其他 > 详细

Permute Digits

时间:2018-01-26 23:42:12      阅读:324      评论:0      收藏:0      [点我收藏+]

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.

Example
Input
123
222
Output
213
Input
3921
10000
Output
9321
Input
4940
5000
Output
4940

在调整过程中要判断大小,本来想是降序排序然后交换顺序,但是123和222,如果按照这样就是321,换3和2,就是231,还是大,然后就会换2和1,答案肯定不对,所以换了以后剩下的保持升序最好,也就是先升序排序,然后倒着把大的跟前面换,然后把剩下的升序排序,一直这么进行下去,纸上模拟了一遍可行。

代码:
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
char s1[20],s2[20],s[20];
bool cmp(char a,char b)
{
    return a > b;
}
int main()
{
    int j;
    cin>>s1>>s2;
    if(strlen(s1) < strlen(s2))
    {
        sort(s1,s1 + strlen(s1),cmp);
    }
    else
    {
        sort(s1,s1 + strlen(s1));
        for(int i = 0;i < strlen(s1);i ++)
        {
            strcpy(s,s1);///保存原来的s1,如果交换不成功,还原,继续尝试其他交换
            for(j = strlen(s1) - 1;j > i;j --)
            {
                swap(s1[i],s1[j]);
                sort(s1 + i + 1,s1 + strlen(s1));
                if(strcmp(s1,s2) <= 0)break;
                else strcpy(s1,s);
            }
        }
    }
    cout<<s1;
}

 

Permute Digits

原文:https://www.cnblogs.com/8023spz/p/8361779.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!