C. Permute Digits
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output
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
#include<bits/stdc++.h>
using namespace std;
#define LL long long
#define clr(a) memset(a,0,sizeof(a))
const int MAXN = 1e5+10;
const int INF = 0x3f3f3f3f;
const int N = 101;
char s[N],a[N];
int vis[N],b[N],res[N];
int flag,l1,l2;
void dfs(int pos,bool check){
if(flag) return ;
if(pos == l1){
flag = true ; return;
}
for(int i=9;i>=0;i--){
if(vis[i]>0){
if(check || i == b[pos]){
vis[i] --;
res[pos] = i;
dfs(pos + 1,check);
if(flag) return;
vis[i] ++;
}
else if(i < b[pos]){
vis[i] --;
res[pos] = i;
dfs(pos+1,true);
if(flag) return ;
vis[i]++;
}
}
}
}
bool cmp(char a,char b){
return a > b;
}
int main(){
flag = false;
scanf("%s %s",s,a);
l1 = strlen(s);
l2 = strlen(a);
sort(s,s+l1,cmp);
if(l2 > l1) puts(s);
else if(l2 == l1&&strcmp(s,a)<0) puts(s);
else{
for(int i=0;i<l1;i++)
vis[s[i]-'0'] ++;
for(int i=0;i<l2;i++)
b[i] = a[i] - '0';
dfs(0,false);
for(int i=0;i<l1;i++)
printf("%d",res[i]);
cout<<endl;
}
return 0;
}