codeforces 915C. Permute Digits

矫情吗;* 2022-05-09 16:42 307阅读 0赞

题目链接:http://codeforces.com/problemset/problem/915/C

C. Permute Digits

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.

很容易会想a的全排列,但是18!肯定是不行的。

然后就会想统计a中0-9各有几个,然后构造b,但是这样要考虑的太多了,也不可行。

就可以用以下方法啦,先考虑长度,如果b比a长,那直接取a得最大值;否则就考虑a的每一位,先把a从小到大排好,然后用最大值去和a的当前i位换,i位之后的从小到大排(因为此时我只要保证i位换了之后是可行的),记得用c记录一下没换过的a,这样如果换是不可行的,还能把a换回去。

  1. #include<stdio.h>
  2. #include<string.h>
  3. #include<math.h>
  4. #include<iostream>
  5. #include<string>
  6. #include<algorithm>
  7. #include<map>
  8. #include<set>
  9. #include<queue>
  10. #include<vector>
  11. using namespace std;
  12. #define inf 0x3f3f3f3f
  13. #define LL long long
  14. int main()
  15. {
  16. string a,b,c;
  17. cin>>a>>b;
  18. sort(a.begin(),a.end());
  19. if(a.length()<b.length())
  20. {
  21. reverse(a.begin(),a.end());
  22. cout<<a<<endl;
  23. }
  24. else
  25. {
  26. for(int i=0;i<a.length();i++)
  27. {
  28. for(int j=a.length()-1;j>i;j--)
  29. {
  30. c=a;
  31. swap(a[i],a[j]);
  32. sort(a.begin()+i+1,a.end());
  33. if(a>b)
  34. {
  35. a=c;
  36. }
  37. else
  38. break;
  39. }
  40. }
  41. cout<<a<<endl;
  42. }
  43. }

发表评论

表情:
评论列表 (有 0 条评论,307人围观)

还没有评论,来说两句吧...

相关阅读