fork download
  1. #include <iostream>
  2. #include <algorithm>
  3. #include <vector>
  4. #include <string>
  5. using namespace std;
  6.  
  7. int arr[11 + 1];
  8. int chk[11 + 1];
  9. string a, b;
  10.  
  11. vector<int> v;
  12.  
  13. string ans = "0";
  14.  
  15. int dfs(int cnt) {
  16. if (cnt == a.size()) {
  17. //조합 잘 수행되는지 확인
  18. //for (int i = 0; i < b.size(); ++i) {
  19. // cout << v[i] << " ";
  20. //}
  21. //cout << endl;
  22.  
  23. string ss = "";
  24. for (int i = 0; i < v.size(); ++i) {
  25. if (v[0] == 0) return 0;
  26. ss += v[i] + '0';
  27. }
  28.  
  29. if (stol(ans) < stol(ss) && stol(ss) <= stol(b)) {
  30. ans = ss;
  31. }
  32. else if (stol(ss) > stol(b)) {//출력 후 종료
  33. if (ans != "0") {
  34. cout << ans << endl;
  35. exit(0);
  36. }
  37. else {
  38. cout << -1 << endl;
  39. exit(0);
  40. }
  41. }
  42. return 0;
  43. }
  44.  
  45. for (int i = 0; i < a.size(); ++i) {
  46. if (cnt == 0 && a[i] == '0') continue;
  47. if (!chk[i]) {
  48. chk[i] = 1;
  49. v.push_back(arr[i]);
  50.  
  51. dfs(cnt + 1);
  52.  
  53. chk[i] = 0;
  54. v.pop_back();
  55. }
  56. }
  57.  
  58. return 0;
  59. }
  60.  
  61. //조합
  62. int main() {
  63. cin >> a >> b;
  64.  
  65. for (int i = 0; i < a.size(); ++i) {
  66. arr[i] = a[i] - '0';
  67. }
  68. sort(arr, arr + a.size());//1 2 3 4
  69.  
  70. dfs(0);
  71.  
  72. if (ans != "0") {
  73. cout << ans << endl;
  74. }
  75. else {
  76. cout << -1 << endl;
  77. }
  78. }
Success #stdin #stdout 0s 4428KB
stdin
789 123
stdout
-1