CodeForces - 288C Polo the Penguin and XOR operation
Little penguin Polo likes permutations. But most of all he likes permutations of integers from 0 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 numbers x and y. This operation exists in all modern programming languages, for example, in language C++ and Java it is represented as “^” and in Pascal — as “xor”.
Help him find among all permutations of integers from 0 to n 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 from 0 to n with the beauty equal to m.
If there are several suitable permutations, you are allowed to print any of them.
Examples
Input
4
Output
20
0 2 1 4 3
讲真,这是头一次碰到需要异或的题(或者是以前碰到没理),虽然代码很短但是理解起来确实有一定的难度……
#include<cstdio>
#include<iostream>
#include<cmath>
#include<algorithm>
#include<string>
#include<cstring>
#include <cctype>
#include <stack>
#define N 200100
using namespace std;
typedef long long ll;
const int INF=0x3f3f3f3f;
const int maxn=35;
int vis[1000100];
int main(){
int n,i,lv,num,tmp;
long long sum;
sum=0;
scanf("%d",&n);
for(i=n;i>=1;i--){
if(vis[i]){
continue;
}
lv=log2(i)+1;
num=(1<<lv)-1;
tmp=num^i;
vis[tmp]=i;
vis[i]=tmp;
}
for(i=0;i<=n;i++){
sum+=i^vis[i];
}
printf("%lld\n",sum);
for(i=0;i<=n;i++){
printf("%d ",vis[i]);
}
return 0;
}