#include <iostream> #include <vector> using namespace std; // Useful links: // https://en.wikipedia.org/wiki/Subset_sum_problem // https://www.geeksforgeeks.org/subset-sum-problem-dp-25/ // https://oeis.org/search?q=1%2C4%2C12%2C32%2C80%2C192&sort=&language=english&go=Search // https://oeis.org/A001787 // To count number of set bits int countSetBits(int n) { int count = 0; while (n) { n &= (n - 1); count++; } return count; } void display(const vector<int>& v) { for (int i = 0; i < v.size(); ++i) printf("%d ", v[i]); printf("\n"); } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int n; cin >> n; //-------------------------------------------------- int series = 0; int two_to_power_of_k = 1; while (true) { series = two_to_power_of_k + 2 * series; two_to_power_of_k = 2 * two_to_power_of_k; if (series > n) { break; } } //---------------------------------------------------- vector<int> bits_set; vector<int> result; for (int i = 0; i < two_to_power_of_k; i++) { bits_set.push_back(countSetBits(i)); } vector<bool> remove(bits_set.size()); int sum = series; int i = bits_set.size() - 1; while (sum > n) { if (sum - bits_set[i] >= n) { sum = sum - bits_set[i]; remove[i] = true; } i--; } for (int i = bits_set.size() - 1; i > 0; i--) { if (!remove[i]) { result.push_back(i); } } cout << result.size() << std::endl; display(result); }
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 79 80 81 82 83 84 85 86 87 88 | #include <iostream> #include <vector> using namespace std; // Useful links: // https://en.wikipedia.org/wiki/Subset_sum_problem // https://www.geeksforgeeks.org/subset-sum-problem-dp-25/ // https://oeis.org/search?q=1%2C4%2C12%2C32%2C80%2C192&sort=&language=english&go=Search // https://oeis.org/A001787 // To count number of set bits int countSetBits(int n) { int count = 0; while (n) { n &= (n - 1); count++; } return count; } void display(const vector<int>& v) { for (int i = 0; i < v.size(); ++i) printf("%d ", v[i]); printf("\n"); } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int n; cin >> n; //-------------------------------------------------- int series = 0; int two_to_power_of_k = 1; while (true) { series = two_to_power_of_k + 2 * series; two_to_power_of_k = 2 * two_to_power_of_k; if (series > n) { break; } } //---------------------------------------------------- vector<int> bits_set; vector<int> result; for (int i = 0; i < two_to_power_of_k; i++) { bits_set.push_back(countSetBits(i)); } vector<bool> remove(bits_set.size()); int sum = series; int i = bits_set.size() - 1; while (sum > n) { if (sum - bits_set[i] >= n) { sum = sum - bits_set[i]; remove[i] = true; } i--; } for (int i = bits_set.size() - 1; i > 0; i--) { if (!remove[i]) { result.push_back(i); } } cout << result.size() << std::endl; display(result); } |