#include <bits/stdc++.h> using namespace std; long long bits1toN(long long n) { long long acc = 0; while (n) { int lg = __lg(n); int pow = 1 << lg; n = n ^ pow; acc += lg * pow / 2 + n + 1; } return acc; } constexpr int step = 256; int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); int n; cin >> n; // Binary search is faster, but not required as n is less than 10^6 int top = step; int val; vector<int> incl; while ((val = bits1toN(top)) < n) { top += step; } while (val != n) { int bits = __builtin_popcount(top); if (__builtin_expect(val - bits < n, 0)) { incl.push_back(top); } else { val -= bits; } top--; } cout << incl.size() + top << '\n'; for (auto i : incl) { cout << i << ' '; } for (int i = top; i > 1; i--) { cout << i << ' '; } cout << "1\n"; }
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 | #include <bits/stdc++.h> using namespace std; long long bits1toN(long long n) { long long acc = 0; while (n) { int lg = __lg(n); int pow = 1 << lg; n = n ^ pow; acc += lg * pow / 2 + n + 1; } return acc; } constexpr int step = 256; int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); int n; cin >> n; // Binary search is faster, but not required as n is less than 10^6 int top = step; int val; vector<int> incl; while ((val = bits1toN(top)) < n) { top += step; } while (val != n) { int bits = __builtin_popcount(top); if (__builtin_expect(val - bits < n, 0)) { incl.push_back(top); } else { val -= bits; } top--; } cout << incl.size() + top << '\n'; for (auto i : incl) { cout << i << ' '; } for (int i = top; i > 1; i--) { cout << i << ' '; } cout << "1\n"; } |