fork(1) download
  1. #include <bits/stdc++.h>
  2. #define int long long
  3. using namespace std;
  4. const int N = 1e5;
  5. int a[205],c[N+5];
  6. string p, s;
  7. void solve()
  8. {
  9. cin >> p >> s;
  10. for (int i = 0; i < s.size(); i++)
  11. {
  12. a[s[i]] = 1;
  13. }
  14. int si = 0;
  15. bool check = false;
  16. for (int j = 0; j < p.size(); j++)
  17. {
  18. if (a[p[j]] == 1)
  19. {
  20. if (!check)
  21. {
  22.  
  23. for (int i = p[j]; i >= '0'; i--)
  24. {
  25. if (a[i] == 0)
  26. {
  27. c[si++] = (char)i;
  28.  
  29. break;
  30. }
  31. }
  32.  
  33. check = true;
  34. }
  35. else
  36. {
  37.  
  38. for (int i = '9'; i >= '0'; i--)
  39. {
  40. if (a[i] == 0)
  41. {
  42. c[si++] = (char)i;
  43.  
  44. break;
  45. }
  46. }
  47.  
  48. }
  49. }
  50. else
  51. {
  52. if (!check)
  53. {
  54. c[si++] = p[j];
  55. }
  56. else
  57. {
  58.  
  59. for (int i = '9'; i >= p[j]; i--)
  60. {
  61. if (a[i] == 0)
  62. {
  63. c[si++] = (char)i;
  64.  
  65. break;
  66. }
  67. }
  68.  
  69. }
  70. }
  71. }
  72. if (si == 0)
  73. {
  74. cout << -1;
  75. return;
  76. }
  77. int vt = 0;
  78. while (vt < si && c[vt] == '0')
  79. {
  80. vt++;
  81. }
  82. if (vt == si)
  83. {
  84. cout << -1;
  85. return;
  86. }
  87. for (int i = vt; i < si; i++)
  88. cout << char(c[i]);
  89. }
  90. signed main()
  91. {
  92. freopen("BAI3.INP", "r", stdin);
  93. freopen("BAI3.OUT", "w", stdout);
  94. ios_base::sync_with_stdio(0);
  95. cin.tie(0);
  96. cout.tie(0);
  97. solve();
  98. }
  99.  
Success #stdin #stdout 0.01s 5284KB
stdin
Standard input is empty
stdout
Standard output is empty