Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<bits/stdc++.h>
- using namespace std;
- #define int long long
- int get(vector<int> cnt, int n) {
- int len = 0;
- for(int x : cnt) len += x;
- string s = to_string(n);
- if(len < s.length() || len > s.length()+1) return -1;
- string ans;
- if(len > s.length()) goto put_increasing;
- for(char c : s){
- int dig = c-'0';
- if(cnt[dig]) ans += c, cnt[dig]--;
- else {
- for(int d = dig+1; d <= 9; d++) {
- if(cnt[d]) {
- ans += d + '0';
- cnt[d]--;
- goto put_increasing;
- }
- }
- return -1;
- }
- }
- put_increasing:
- for(int dig = 1; dig <= 9; dig++) while(cnt[dig]--) ans += dig+'0';
- int res = stoll(ans);
- if(res == n) return -1;
- return res;
- }
- int solve(int n) {
- int ans = 99999999988888888;
- for(int mask = 0; mask < (1<<9); mask++) {
- vector<int> cnt(10);
- for(int dig = 1; dig <= 9; dig++) {
- if(mask >> (dig-1) & 1) cnt[dig] = dig;
- }
- int best = get(cnt, n);
- if(best != -1) ans = min(ans, best);
- }
- return ans;
- }
- #undef int
- int main() {
- int n; cin >> n ;
- cout << solve(n);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement