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;
    }
  • 相关阅读:
    加载数据量大,页面卡死解决办法
    [存档]开启window7的隐藏功能虚拟wifi
    IIS发布Asp.Net网站注意事项
    [转载]总结几种C#窗体间通讯的处理方法
    调整和删除Win7休眠文件Hiberfil.sys的方法技巧,释放系统空间! ...
    [存档]Div+Css布局中经常使用的小技巧合集
    Android AndroidManifest.xml 结构详解
    Android权限详细说明
    Activity 生命周期详解
    程序员的文采
  • 原文地址:https://www.cnblogs.com/8023spz/p/8361779.html
Copyright © 2011-2022 走看看