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.
Examples
input
1 | 123 |
output
1 | 213 |
input
1 | 3921 |
output
1 | 9321 |
input
1 | 4940 |
output
1 | 4940 |
- b一定不短于a
- 如果b比a长,直接降序排列a
- 如果一样长
- 先统计a中数字的个数
- 对于每一位b,都找不比b大的匹配,一旦有一位匹配后小于b的那位,之后就可以从最大的开始降序匹配
- 如果有一位无法匹配小于等于b的那位,那么就回退一位,匹配小于b的,这样后面就可以不受约束
C++ Code
1 |
|