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
#include <iostream>
#include <climits>
#include <array>

using std::cin, std::cout;
const char endl = '\n';

int main()
{
    std::ios_base::sync_with_stdio(false);
    cin.tie(NULL);    

    unsigned int n;
    cin >> n;
    __builtin_popcount(n);

    unsigned int popcountsum = 0;

    // ceil log2 1 000 000 = 20
    std::array<unsigned int, 20+7> lastFoundPopcount = {0};
    unsigned int maxNum;
    for (maxNum = 1; popcountsum < n; maxNum++)
    {
        unsigned int popcount = __builtin_popcount(maxNum);
        popcountsum += popcount;
        lastFoundPopcount.at(popcount) = maxNum;
    }
    maxNum--;

    unsigned int delta = popcountsum - n;
    unsigned int removedIndex = INT_MAX;
    if (delta != 0) 
    {
        removedIndex = lastFoundPopcount[delta];
        cout << maxNum-1 << endl;
    }
    else cout << maxNum << endl;
    
    for (int i = maxNum; i >= 1; i--)
    {
        if (i != removedIndex) cout << i << ' ';
    }
    
}