您的位置:首页 > 产品设计 > UI/UE

CF 288C (Polo the Penguin and XOR operation)

2013-08-15 09:24 609 查看
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: