#include<iostream> #include<string> #include<bitset> #include<utility> #include<vector> int popcount(int i) { return std::bitset<32>(i).count(); } std::pair<int, int> getClosesSum(int n) { int i = 0; int sum = 0; for(;sum<n; ++i) { sum += popcount(i); } i--; return {i, sum}; } void calc(int n) { auto [i, sum] = getClosesSum(n); if (sum == n) { std::cout << i << std::endl; for (;i>1; --i) std::cout << i << " "; std::cout << i << std::endl; return; } std::vector<int> results; for(;i>0; --i) { int bits = popcount(i); if (sum-bits >= n) { sum -= bits; continue; } results.push_back(i); } std::cout << results.size() << std::endl; std::cout << results[0]; for (i=1;i<results.size(); ++i) std::cout << " " << results[i]; std::cout << std::endl; // std::cout << i << " " << sum << std::endl; } int main() { int n; std::cin >> n; calc(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 | #include<iostream> #include<string> #include<bitset> #include<utility> #include<vector> int popcount(int i) { return std::bitset<32>(i).count(); } std::pair<int, int> getClosesSum(int n) { int i = 0; int sum = 0; for(;sum<n; ++i) { sum += popcount(i); } i--; return {i, sum}; } void calc(int n) { auto [i, sum] = getClosesSum(n); if (sum == n) { std::cout << i << std::endl; for (;i>1; --i) std::cout << i << " "; std::cout << i << std::endl; return; } std::vector<int> results; for(;i>0; --i) { int bits = popcount(i); if (sum-bits >= n) { sum -= bits; continue; } results.push_back(i); } std::cout << results.size() << std::endl; std::cout << results[0]; for (i=1;i<results.size(); ++i) std::cout << " " << results[i]; std::cout << std::endl; // std::cout << i << " " << sum << std::endl; } int main() { int n; std::cin >> n; calc(n); return 0; } |