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

    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;
    }
  • 相关阅读:
    机器学习回顾篇(14):主成分分析法(PCA)
    Elasticsearch系列---前缀搜索和模糊搜索
    Elasticsearch系列---近似匹配
    Elasticsearch系列---多字段搜索
    Elasticsearch系列---深入全文搜索
    Elasticsearch系列---shard内部原理
    Elasticsearch系列---结构化搜索
    01、Spring环境搭建
    02、Hibernate开发步骤
    01、Hibernate安装配置
  • 原文地址:https://www.cnblogs.com/8023spz/p/8361779.html
Copyright © 2020-2023  润新知