Advertisement
vinayak7989

Untitled

Sep 26th, 2022
560
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.41 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3.  
  4. #define int long long
  5.  
  6. int get(vector<int> cnt, int n) {
  7.       int len = 0;
  8.       for(int x : cnt) len += x;
  9.       string s = to_string(n);
  10.       if(len < s.length() || len > s.length()+1) return -1;
  11.       string ans;
  12.       if(len > s.length()) goto put_increasing;
  13.       for(char c : s){
  14.             int dig = c-'0';
  15.             if(cnt[dig]) ans += c, cnt[dig]--;
  16.             else {
  17.                   for(int d = dig+1; d <= 9; d++) {
  18.                         if(cnt[d]) {
  19.                               ans += d + '0';
  20.                               cnt[d]--;
  21.                               goto put_increasing;
  22.                         }                        
  23.                   }
  24.                   return -1;
  25.             }
  26.       }
  27.       put_increasing:
  28.       for(int dig = 1; dig <= 9; dig++) while(cnt[dig]--) ans += dig+'0';
  29.       int res = stoll(ans);
  30.       if(res == n) return -1;
  31.       return res;
  32. }
  33.  
  34. int solve(int n) {
  35.       int ans = 99999999988888888;
  36.       for(int mask = 0; mask < (1<<9); mask++) {
  37.             vector<int> cnt(10);
  38.             for(int dig = 1; dig <= 9; dig++) {
  39.                   if(mask >> (dig-1) & 1) cnt[dig] = dig;
  40.             }
  41.             int best = get(cnt, n);
  42.             if(best != -1) ans = min(ans, best);
  43.       }
  44.       return ans;
  45. }
  46.  
  47. #undef int
  48.  
  49. int main() {
  50.       int n; cin >> n ;
  51.       cout << solve(n);
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement