CodeForces 288C Polo the Penguin and XOR operation



题意:给一个数 n,求0~n的一个排列,使得这个排列与0-n的对应异或之和最大。
分析:两个数二进制数正好互补,异或就是最大的,比如,一个数是100,那么我们要找11,(都是二进制)
就是这样找,而且两两正好配对,如果多了一个就是0。怎么找那另一个和它互补的数呢?用11...1 - 本身

借鉴了MZH的代码

#include<stdio.h>
#include<iostream>
#include<math.h>
#include<string.h>
#include<iomanip>
#include<stdlib.h>
#include<ctype.h>
#include<algorithm>
#include<deque>
#include<functional>
#include<iterator>
#include<vector>
#include<list>
#include<map>
#include<queue>
#include<set>
#include<stack>
#include<sstream>
#define CPY(A, B) memcpy(A, B, sizeof(A))
typedef long long LL;
typedef unsigned long long uLL;
const int MOD = 1e9 + 7;
const int INF = 0x3f3f3f3f;
const LL INFF = 0x3f3f3f3f3f3f3f3fLL;
const double EPS = 1e-9;
const double OO = 1e20;
const double PI = acos (-1.0);
int dx[]= {0,1,1,1,0,-1,-1,-1};
int dy[]= {1,1,0,-1,-1,-1,0,1};
int gcd (const LL &a, const LL &b) {return b==0?a:gcd (b,a%b);}
using namespace std;
const int maxn=1e6+10;
int a[maxn];
int bitcnt (int n) {
    int cnt=0;
    while (n) {
        n=n>>1; cnt++;
    }
    return cnt;
}
map<LL,LL>pos;
int main() {
    memset (a,0,sizeof (a) );
    int n; scanf ("%d",&n);
    for (int i=n; i>=0; --i) {
        int len=bitcnt (i);//获取位数
        LL maxv= (1<<len)-1;//构造全1的那个二进制数
        if (!pos.count (i) &&!pos.count (maxv^i) ) {
            pos[i]=maxv^i;
            pos[maxv^i]=i;//两两配到一起
        }
    }
    LL sum=0;
    for (int i=0; i<=n; ++i) {sum+=pos[i]^i;}//求和Σi^A[i]
    printf ("%I64d\n",sum);
    for (int i=0; i<=n; ++i) {
        printf ( (i) ?" %I64d":"%I64d",pos[i]);
    }
    return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值