CF 288C (Polo the Penguin and XOR operation)

Description

Little penguin Polo likes permutations. But most of all he likes permutations of integers from0 to n, inclusive.

For permutation p = p0, p1, ..., pn, Polo has defined its beauty — number.

Expression means applying the operation of bitwise excluding "OR" to numbersx and y. This operation exists in all modern programming languages, for example, in languageC++ and Java it is represented as "^" and inPascal — as "xor".

Help him find among all permutations of integers from 0 ton the permutation with the maximum beauty.

Input

The single line contains a positive integer n (1 ≤ n ≤ 106).

Output

In the first line print integer m the maximum possible beauty. In the second line print any permutation of integers from0 to n with the beauty equal tom.

If there are several suitable permutations, you are allowed to print any of them.


Sample Input


Input
4 
Output
20
0 2 1 4 3


题目大意:

给一个数,求它0-n与0-n异或和的最大值

如输入4

序列 0   1   2   3   4

         ^    ^   ^   ^   ^

         0   2   1   4   3   //需要求的序列

          ||   ||   ||   ||   ||

         0   3   3   7   7

sum = 0 + 3 + 3 + 7 + 7 = 20


我的做法是:将0 - 10 的数写成2进制数找规律。


0000     0100     1000

0001     0101     1001

0010     0110     1010

0011     0111


n = 0 序列 0

n = 1 序列 1 0

n = 2 序列 0 2 1

n = 3 序列 3 2 1 0

n = 4 序列 0 2 1 4 3

n = 5 序列 1 0 2 4 3 5

……

可以发现每多出一个数只要将它补足最高位以下满一的形式就可以使序列最大化,那么5 和 2 搭配 然后4 和 3 搭配 1 和 0 搭配即可最大。


#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#define MAXN 1000001

using namespace std;

long long n;

int array[MAXN];
bool vis[MAXN];

void input()
{
    cin >> n;
    cout << (long long)(n * (n + 1)) << endl;           //可以发现

    int num = 0, b = 0, a = 0;

    for (int i = n; i >= 0; i--)
    {
        if (!vis[i])
        {
            num = 0;
            b = i;
            while (b)                                   //求二进制表示最高有几位

            {
                b >>= 1;
                num++;
            }                                           

            a = i ^ ((int)pow(2, num) - 1);
            array[i] = a;
            array[a] = i;
            vis[i] = vis[a] = true;
        }
    }

    for (int i = 0; i <= n; i++)
    {
        printf("%d", array[i]);
        if (i != n)
        {
            printf(" ");
        }
    }
}

int main()
{
    input();
    return 0;
}


你可能感兴趣的:(CF 288C (Polo the Penguin and XOR operation))