【NEEPU OJ】1042--Xor-Sum

本文介绍了一种算法问题,目标是在1到n的整数中选择k个整数,以获得最大的XOR和。通过分析,发现当k大于1时,总是可以获得一个最大值,该值等于某个二进制有效位的2的幂次方减1。
描述

A xor-sum of a sequence of integers a_1, a_2,…a_m is defined as the bitwise XOR of all its elements: a_1⊕a_2⊕…⊕a_m, here ⊕ denotes the bitwise XOR operation which obeys the following rules:

0⊕0=0

0⊕1=1

1⊕0=1

1⊕1=0

Your task is to choose k integers from 1 to n to get the largest xor-sum.

输入

A single line contains two integers n and k (1≤k≤n≤10^18).

输出

Print one integer — the largest xor-sum you can obtain.

输入样例 1

4 3

输出样例 1

7

输入样例 2

6 6

输出样例 2

7

提示

In the first example,one optimal choice is 1, 2 and 4, giving the xor-sum of 7.

In the second example,one can, for example, take all six integers and obtain the xor-sum of 7.

来源

NEEPU 13th ACM


思路

这题是道找规律题:
k=1时,结果一定是n。
假如n=4,k=3,用p来表示二进制数的有效位,那么

1 => 001 (p==1)
2 => 010 (p==2)
3 => 011 (p==2)
4 => 100 (p==3)
         011
XOR 100
           = 111 (7)

所以结果不会超过2p+1-1。
又因为2p和2p-1都不会超过n,而且它们的xor是2p+1-1。因此,当k>1时,总能得到最大值。


代码
#include <iostream>
using namespace std;

int main(){
    long long n, k;
    long long i;
    int c = 0;
    cin >> n >> k;
    if(n >= 1 && k >= 1){
        if(k == 1) cout << n;
        else{
            for(i = 1; c == 0; i *= 2){
                if(n >= i && n < i * 2){
                    cout << i * 2 - 1;
                    c = 1;
                }
            }
        }
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值