题目描述
给出两个整数 A 和 B,可以重新排列 A 得到新的数字 C (不能有前导0)。求在小于等于 B 的情况下,C 的最大值是多少。如果不存在输出 -1。
输入
第一行包含两个整数 A 和 B。 1 <= A, B < 10^9。
输出
输出符合条件情况下C的最大值。
样例输入
1234 3456
样例输出
3421
解题思路:next_permutation全排列函数暴力枚举,先用sort函数从小到大排列好,排除含有前导0的数字排列组合,然后此时已经是最小不含前导0的组合,与B进行比较,若比B大,则肯定没有符合要求的数字排列输出-1,否则则全排列暴力枚举查找出最大符合题意的那个数。
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
int main(){
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
char a[20];cin>>a;
LL b;cin>>b;
LL sum=0;
LL n=strlen(a);
sort(a,a+n);
do{
next_permutation(a,a+n);
}while(a[0]=='0');//排除含有前导0的数字排列组合
for(int i=0;i<n;i++){
sum=sum*10+(a[i]-'0');
}
if(sum>b)cout<<-1<<endl;
else{
bool flag=0;
while(next_permutation(a,a+n)){
LL ans=sum;
sum=0;
for(int i=0;i<n;i++){
sum=sum*10+(a[i]-'0');
}
if(sum>b){
cout<<ans<<endl;
flag=1;
break;
}
}
if(flag==0)cout<<sum<<endl;
}
return 0;
}
题目来源:2020年安徽省省赛