You are given two positive integer numbers a and b. Permute (change order) of the digits of ato 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.
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.
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.
123 222
213
3921 10000
9321
4940 5000
4940
题意:给你一个数小于1e18 a和b,输出不大于b的数a,a是经过重排列了的。
题解:由于数很大,一位一位的找判是不行的。最简单的是转换成字符串做,先sort排序,然后交换n阶乘次相(当于排列组合,判断组合出来的a和b的关系,如果a<=b的,就存入c字符组。又继续找。#include<bits/stdc++.h>
using namespace std;
char a[20],b[20],c[20];
int main()
{
int m;
while(cin>>a>>b)
{
m=strlen(a);
sort(a,a+m);
if(m<strlen(b))
{
for(int i=m-1; i>=0; i--)
cout<<a[i];
return 0;
}
strcpy(c,a);
for(int i=0; i<m; i++)
{
strcpy(a,c);
for(int j=i; j<m; j++)
{
swap(a[i],a[j]);
if(strcmp(a,b)!=1)
strcpy(c,a);
}
}
puts(a);
}
return 0;
}
#include<bits/stdc++.h>
using namespace std;
char a[20],b[20],c[20];
int main()
{
int m;
while(cin>>a>>b)
{
m=strlen(a);
sort(a,a+m);
if(m<strlen(b))
{
for(int i=m-1; i>=0; i--)
cout<<a[i];
return 0;
}
strcpy(c,a);
for(int i=0; i<m; i++)
{
strcpy(a,c);
for(int j=i; j<m; j++)
{
swap(a[i],a[j]);
if(strcmp(a,b)!=1)
strcpy(c,a);
}
}
puts(a);
}
return 0;
}