【CodeForces】--- New Year's Eve(思维)

本文介绍了CodeForces上的一道题目,挑战在新年夜,Grisha如何从Ded Moroz带来的糖果中选择不超过k个,使得糖果的异或和最大化。Grisha的目标是最大化他的幸福度,即糖果的异或和。问题转化为从1到n的整数中,选取不超过k个数,使得异或和最大。当k=1时,最大异或和为n,而当k>=2时,可以找到两个数使得异或结果的二进制表示最高位之后都是1,从而达到最大异或和。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接:Click Click Here

                    B. New Year's Eve
                    time limit per test1 second
                    memory limit per test256 megabytes
                    inputstandard input
                    outputstandard output

Since Grisha behaved well last year, at New Year’s Eve he was visited by Ded Moroz who brought an enormous bag of gifts with him! The bag contains n sweet candies from the good ol’ bakery, each labeled from 1 to n corresponding to its tastiness. No two candies have the same tastiness.

The choice of candies has a direct effect on Grisha’s happiness. One can assume that he should take the tastiest ones — but no, the holiday magic turns things upside down. It is the xor-sum of tastinesses that matters, not the ordinary sum!

A xor-sum of a sequence of integers a1, a2, …, am is defined as the bitwise XOR of all its elements: , here denotes the bitwise XOR operation; more about bitwise XOR can be found here.

Ded Moroz warned Grisha he has more houses to visit, so Grisha can take no more than k candies from the bag. Help Grisha determine the largest xor-sum (largest xor-sum means maximum happiness!) he can obtain.

Input
The sole string contains two integers n and k (1 ≤ k ≤ n ≤ 1018).

Output
Output one number — the largest possible xor-sum.

Examples
input
4 3
output
7
input
6 6
output
7
Note
In the first sample case, one optimal answer is 1, 2 and 4, giving the xor-sum of 7.

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

思路:n和k,从1~n的n个数中,选出最多k个数,使选出的几个数字的异或最大。
分析:k为1,那么最多只选一个数,异或结果最大当然是n。若k不为1,即k大于等于2,则从1到k的k个数中,肯定能找到两个数的异或和,使得,数字n对应的二进制数的最高位‘1’后面的所有二进制位都是‘1’,这样异或的结果最大。那么当k大于等于2时,答案是唯一的。

这里写代码片
#include<cstdio>
typedef long long LL;
int main()
{
    LL n,k;
    while(~scanf("%lld%lld",&n,&k))
    {
        if(k==1)        //k为1
            printf("%lld\n",n);
        else            //k不为1
        {
            LL num=1;       //记录最终结果 
            while(n>>=1)    //n依次右移除以2,循环次数即为n二进制最高位的位数, 
            {
                num<<=1;//每次循环,num左移乘以2,记录下最高位'1'对应的十进制数, 
            }
            printf("%lld\n",(num<<1)-1);//num再乘以2减1得到对应十进制数哦 
        }
    }
    return 0;
 } 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值