#include <stdio.h> #include <deque> int countBits(int n) { int count = 0; while (n) { count += n & 1; n >>= 1; } return count; } std::deque<int> resolve(const int n) { std::deque<int> notes; int totalBits = 0; for (int i = 1; totalBits < n; ++i) { notes.push_front(i); totalBits += countBits(i); } while (n < totalBits) { auto it = notes.begin(); while (it != notes.end()) { const auto diffBits = totalBits - n; const auto bits = countBits(*it); if (bits <= diffBits) { it = notes.erase(it); totalBits -= bits; break; } else { ++it; } } } return notes; } int main() { int n; scanf("%d\n", &n); const auto solution = resolve(n); printf("%lu\n", solution.size()); for (const auto note : solution) { printf("%d ", note); } printf("\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 | #include <stdio.h> #include <deque> int countBits(int n) { int count = 0; while (n) { count += n & 1; n >>= 1; } return count; } std::deque<int> resolve(const int n) { std::deque<int> notes; int totalBits = 0; for (int i = 1; totalBits < n; ++i) { notes.push_front(i); totalBits += countBits(i); } while (n < totalBits) { auto it = notes.begin(); while (it != notes.end()) { const auto diffBits = totalBits - n; const auto bits = countBits(*it); if (bits <= diffBits) { it = notes.erase(it); totalBits -= bits; break; } else { ++it; } } } return notes; } int main() { int n; scanf("%d\n", &n); const auto solution = resolve(n); printf("%lu\n", solution.size()); for (const auto note : solution) { printf("%d ", note); } printf("\n"); return 0; } |