C. Permute Digits
time limit per test1 second
memory limit per test256 megabytes
inputstandard input
outputstandard 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
思路:首先判断a的长度若小于b的长度,则输出a从小到大的字典序。
然后从小到大排列a。依次枚举a[i]与最大的数交换,后面的数从小到大按照字典序排列,此时a的字典序若小于b的字典序,则a[i]变成交换的最大数,否则不能交换。
#include<bits/stdc++.h>
using namespace std;
typedef long long int ll;
const int N=10000+10;
int main()
{
string s1,s2;
int x=0,y=0;
cin>>s1>>s2;
x=s1.length();
y=s2.length();
sort(s1.begin(),s1.end());
if(x<y)
{
reverse(s1.begin(),s1.end());
cout<<s1<<endl;
return 0;
}
string temp;
for(int i=0;i<x;i++)
{
for(int j=x-1;j>i;j--)
{
temp=s1;
swap(s1[i],s1[j]);
sort(s1.begin()+i+1,s1.end());
if(s1.compare(s2)>0)
{
s1=temp;
}
else
{
break;
}
}
}
cout<<s1<<endl;
return 0;
}