zoukankan      html  css  js  c++  java
  • 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;
    }
  • 相关阅读:
    mysql 索引
    springboot + maven jar打包和linux部署
    个人项目———Java实现WordCount
    第四周助教观察记录
    第三周助教工作观察记录
    2019年春-软件工程原理与方法-助教总结
    第十五周助教小结
    第十一周助教小结
    团队作业-设计 成绩汇总
    团队作业选题及需求分析成绩汇总
  • 原文地址:https://www.cnblogs.com/8023spz/p/8361779.html
Copyright © 2011-2022 走看看