#include <bits/stdc++.h> using namespace std; #define pb push_back #define fi first #define sn second typedef long long ll; typedef vector<int> VI; typedef vector<char> VC; typedef pair<int, int> PI; int count_bits(int x) { int r = 0; while (x > 0) { if (x & 1) r++; x >>= 1; } return r; } void solve(int n) { stack<int> S[20]; int total = 0; int current = 1; while (total < n) { int bits = count_bits(current); S[bits].push(current); total += bits; current += 1; } // int tries = 0; while (total > n) { int diff = total - n; for (int i = diff; i >= 1; i--) { if (S[i].size() > 0) { total -= i; S[i].pop(); break; } } // tries += 1; // if (tries > 1000) return -1; } int nums = 0; for (int i = 0; i < 20; i++) nums += S[i].size(); VI R(nums); int j = 0; for (int i = 0; i < 20; i++) { while (!S[i].empty()) { R[j] = S[i].top(); j++; S[i].pop(); } } sort(R.rbegin(), R.rend()); cout << nums << endl; for (int x : R) { cout << x << " "; } cout << endl; } int main() { int n; cin >> n; solve(n); return 0; }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 | #include <bits/stdc++.h> using namespace std; #define pb push_back #define fi first #define sn second typedef long long ll; typedef vector<int> VI; typedef vector<char> VC; typedef pair<int, int> PI; int count_bits(int x) { int r = 0; while (x > 0) { if (x & 1) r++; x >>= 1; } return r; } void solve(int n) { stack<int> S[20]; int total = 0; int current = 1; while (total < n) { int bits = count_bits(current); S[bits].push(current); total += bits; current += 1; } // int tries = 0; while (total > n) { int diff = total - n; for (int i = diff; i >= 1; i--) { if (S[i].size() > 0) { total -= i; S[i].pop(); break; } } // tries += 1; // if (tries > 1000) return -1; } int nums = 0; for (int i = 0; i < 20; i++) nums += S[i].size(); VI R(nums); int j = 0; for (int i = 0; i < 20; i++) { while (!S[i].empty()) { R[j] = S[i].top(); j++; S[i].pop(); } } sort(R.rbegin(), R.rend()); cout << nums << endl; for (int x : R) { cout << x << " "; } cout << endl; } int main() { int n; cin >> n; solve(n); return 0; } |