#include <iostream> #include <vector> #include <algorithm> using namespace std; int count_bits(unsigned int n) { int ct = 0; while(n) { ct += n & 1; n >>= 1; } return ct; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int n; cin >> n; int cr = 0; vector<int> res; int i = 1; while(cr < n) { res.push_back(i); cr += count_bits(i); ++i; } while(cr > n) { int diff = cr-n; int maxi = 0; for(int i = res.size()-2; i >= 0; --i) { int ctb = count_bits(res[i]); if(ctb <= diff) { maxi = i; break; } } int vb = count_bits(res[maxi]); cr -= vb; res.erase(res.begin()+maxi); } reverse(res.begin(), res.end()); cout << res.size() << '\n'; for(int i = 0; i < res.size(); ++i) { cout << res[i] << ' '; } cout << '\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 | #include <iostream> #include <vector> #include <algorithm> using namespace std; int count_bits(unsigned int n) { int ct = 0; while(n) { ct += n & 1; n >>= 1; } return ct; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int n; cin >> n; int cr = 0; vector<int> res; int i = 1; while(cr < n) { res.push_back(i); cr += count_bits(i); ++i; } while(cr > n) { int diff = cr-n; int maxi = 0; for(int i = res.size()-2; i >= 0; --i) { int ctb = count_bits(res[i]); if(ctb <= diff) { maxi = i; break; } } int vb = count_bits(res[maxi]); cr -= vb; res.erase(res.begin()+maxi); } reverse(res.begin(), res.end()); cout << res.size() << '\n'; for(int i = 0; i < res.size(); ++i) { cout << res[i] << ' '; } cout << '\n'; return 0; } |