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
123
222
Output
213
Input
3921
10000
Output
9321
Input
4940
5000
Output
4940
题意:
重新排列第一个数,使其成为不大于第二个数的最大的数
DFS搜一搜,比赛时没想到,一直在想特殊样例。
#include<stdio.h>
#include<algorithm>
#include<string.h>
using namespace std;
char a[20],b[20],ans[20];
int vis[10];
int n,m;
int cut;
void dfs(int x,int falg) {//x表示当前位置,falg表示之前的位置的数是否可以让接下来的数从大到小排列
if(x==n) {
cut=1;//搜索结束条件
return;
}
for(int i=9; i>=0; --i) {
if(vis[i]) {
if(falg||b[x]-'0'==i) {
ans[x]=i+'0';
vis[i]--;
dfs(x+1,falg);
if(cut)return;//如果已经搜到正确答案,结束搜索
vis[i]++;
} else if(i<b[x]-'0') {
ans[x]=i+'0';
vis[i]--;
dfs(x+1,1);
if(cut)return;//如果已经搜到正确答案,结束搜索
vis[i]++;
}
}
}
}
int main() {
scanf("%s",a);
scanf("%s",b);
n=strlen(a);
m=strlen(b);
if(m>n) {
sort(a,a+n);
for(int i=n-1; i>=0; --i) {
printf("%c",a[i]);//倒序输出
}
} else {
for(int i=0; i<n; ++i) {
vis[a[i]-'0']++;
}
cut=0;
dfs(0,0);
printf("%s",ans);
}
return 0;
}
非常自闭的一场比赛,甚至把我自闭回了家,表示各种不服。