Codeforces Round #456 Div.2 B. New Year's Eve

本文解析了CodeForces平台上的一道题目B,探讨如何选取不超过k个整数(1到n之间)来获得最大的异或结果。文章通过示例说明了当k大于1时,结果取决于n的二进制位数,并提供了Python和C语言的实现代码。

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

Problem

codeforces.com/contest/912/problem/B

Analysis

You can choose k or less than k integers from 1~n, calculate maximum xor result
(1) k = 1, You can only choose one integer, so you choose n and get the maximum xor result n
(2) k > 1, whatever k is, such as k = 2, or k = 3, ……, or k = n,
if n has x bits as binary code, the maximum xor result must be 2 ^ x - 1

本题是求从1~n个数中取小于或等于k个数(比如n = 4, k = 3表示从1~4中取1个数或2个数或3个数),对这些数进行异或求和,求最大的异或求和值。
(1)k = 1时,即从1~n个数中1个数,那么最大的数自然是n。结果为n
(2)k > 1时,假如n以二进制表示是x位数,则结果必为2 ^ x - 1

Example 1

n = 4, k = 2
choose 4 and 3, maximum = 4 xor 3 = 7
可以取4和3这两个数,最大异或结果 = 4 xor 3 = 7 = 2 ^ 3 - 1

Example 2

n = 4, k = 3
Choose two numbers, 4 and 3. Or choose three numbers, 4, 1 and 2.
maximum = 4 xor 3 = 4 xor 1 xor 2 = 7 = 2 ^ 3 - 1
可以取4和3这两个数,也可以取4、1、2这三个数。
最大异或结果 = 4 xor 3 = 4 xor 1 xor 2 = 7 = 2 ^ 3 - 1

Example 3

n = 4, k = 4
Choose two numbers, 4 and 3. Or choose three numbers, 4, 1 and 2.
maximum = 7 = 2 ^ 3 - 1
You can not choose all for numbers, because 4 xor 1 xor 2 xor 3 xor 4 = 3, which is not the maximum result.
可以取4和3,也可以取4、1、2。最大异或结果为7。
但不能取4、1、2、3。因为4 xor 1 xor 2 xor 3 xor 4 = 3,不是最大的结果。

Example 4

n = 6, k = 6
Just choose 1 and 6, maximum = 6 xor 1 = 7 = 2 ^ 3 - 1
只要在1~6中取6和1两个数就行了,6 xor 1 = 7 = 2 ^ 3 - 1

Code

Python2

import sys

n, k = map(int, raw_input().split())

if 1 == k:
    print n
    sys.exit(0)

res = 1
while res < n:
    res = res * 2 + 1

print res

C Language

#include <stdio.h>
#include <stdint.h>

int main(void)
{
    int64_t n, k;
    scanf("%I64d %I64d", &n, &k);

    if (1 == k) 
    {
        printf("%I64d\n", n);

        return 0;
    }

    int bit = 0;
    for (; n >> bit; bit++);
    printf("%d", n);
    printf("%d", bit);

    printf("%I64d\n", (1LL << bit) - 1);

    return 0;
}



更多内容请关注微信公众号
wechat.jpg

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值