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.
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.
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.
123 222
213
3921 10000
9321
4940 5000
4940
思路:首先将a的所有数位找出并排序,然后从高位到低位,数字从大到小逐个尝试。选定某个数位后,将之后的数字组合为最小的组合,将新得到的数字a与b比较,若a<b,则说明该位的数字选取成功,反之则将该位选取较小的数字再次尝试。本题中,使用字符串会简单些。
用爆搜貌似也能过
代码如下:
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
bool cmp(char x,char y)
{
return x>y;
}
int main()
{
string a,b;
while (cin>>a>>b){
int alen=a.size();
int blen=b.size();
if (alen<blen){
sort(a.begin(),a.end(),cmp);
cout<<a<<endl;
continue;
}
else{
sort(a.begin(),a.end());
string tmp;
//对于每个数位从大数到小数逐个尝试是否可行,最后得到的一定是尽可能大的数
for (int i=0;i<alen;i++){
for (int j=alen-1;j>=0;j--){
tmp=a;
swap(a[i],a[j]);
sort(a.begin()+i+1,a.end());
if (a>b)
a=tmp;
else
break;
}
}
cout<<a<<endl;
}
}
return 0;
}