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 <iostream>
#include <string.h>
#include <string>
#include <cmath>
#include <algorithm>
#include <stack>
#include <queue>
#include <cstdio>
#include <bitset>
#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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值