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
import java.util.Arrays;
import java.util.Scanner;
public class Main{
static String a,b;
static int [] arr = new int[20];
static int [] boka = new int[10];
static int [] brr = new int[20];
static int [] bokb = new int[10];
static int [] ans = new int[20];
static boolean f=false;
public static void dp(int pos,boolean res){//两字符串长度相等时调用dp
if(f)return;
if(pos>=a.length()){//停止递归,return
f=true;
return;
}
// for(int i=0;i<a.length();i++)
// System.out.print(ans[i]);
// System.out.println("");
int lim = res==false? 9 : brr[pos];//若res为false,lim=9,否则将第二个数的第pos个值赋给lim
for(int i=lim;i>=0;i--){
if(boka[i]>0){//第一个数从后往前看,若大于0,移除此数,并将i赋值给ans[pos]。
boka[i]--;
ans[pos] = i;//得到的答案第一个数为i
dp(pos+1,res&&i==lim);
if(f)return;//找到一个结果就是最大的了 不必继续找了 每次枚举范围都是从大到小
boka[i]++;
}
}
return;
}
public static void main(String [] args){
Scanner sc = new Scanner(System.in);
a = sc.next();
b = sc.next();
System.out.println(a.length());
for(int i=0;i<a.length();i++){
arr[i] = a.charAt(i)-'0';//charAt()方法返回指定索引位置的char值。索引范围为0~length()-1.
boka[a.charAt(i)-'0']++; // 得到arr[i]中存储的数字字符对应boka数组中哪一个下标,也是将字符转成数字,再记数加一。
}
for(int i=0;i<b.length();i++){
brr[i] = b.charAt(i)-'0';
bokb[b.charAt(i)-'0']++;
}
if(a.length()==b.length()){
dp(0,true);
for(int i=0;i<a.length();i++)
System.out.print(ans[i]);
}
else{
Arrays.sort(arr, 0, a.length());
for(int i=a.length()-1;i>=0;i--)
System.out.print(arr[i]);
}
System.out.println("");
}
}