描述
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;
}