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
123222
Output
213
Input
392110000
Output
9321
Input
49405000
Output
4940
题意:
给定两个数字a和b,重新构建a,使a≤b的同时,a是该情况下的最大值。
思路:
(1) 先判断a与b的长度,若a的长度<b的长度,那么直接输出a的降序。
(2) 否则,令a升序排列。L指向a的最高位,R指向a的最低位。依次交换a[L]和a[R](将最大数与最小数进行交换),最高位后面的数按照升序排序。如果a<b,则将a[L]变成a[R],否则不能交换。
例:a=78135,b=55634 (a按升序排序为:13578)
<1> 81357->71358->51378 (确定第五位是5)
<2> 58137->57138->53178 (确定第四位是3)
<3> 53817 (确定第三位是1)
<4> 53871 (确定第二、第一位分别为7、1)
#include<algorithm> #include<iostream> #include<string> using namespace std; int main() { string a,b,t; cin>>a>>b; int lena=a.length(),lenb=b.length(); sort(a.begin(),a.end()); if(lena<lenb) reverse(a.begin(),a.end()); else { int L,R; for(L=0;L<lena;L++) { R=lena-1; t=a; while(R>L) { swap(a[L],a[R--]); sort(a.begin()+L+1,a.end()); if(a>b)a=t; else break; } } } cout<<a<<endl; return 0; }
原文地址:https://www.cnblogs.com/kannyi/p/9634203.html