AtCoder:A or...or B Problem(思维)

探讨给定区间内任意数按位或运算结果的可能性数量,通过寻找关键分界点来简化问题,实现高效求解。

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

D - A or...or B Problem


Time limit : 2sec / Memory limit : 256MB

Score : 900 points

Problem Statement

Nukes has an integer that can be represented as the bitwise OR of one or more integers between A and B (inclusive). How many possible candidates of the value of Nukes's integer there are?

Constraints

  • 1AB<260
  • A and B are integers.

Input

The input is given from Standard Input in the following format:

A
B

Output

Print the number of possible candidates of the value of Nukes's integer.


Sample Input 1

Copy
7
9

Sample Output 1

Copy
4

In this case, A=7 and B=9. There are four integers that can be represented as the bitwise OR of a non-empty subset of {789}: 789 and 15.


Sample Input 2

Copy
65
98

Sample Output 2

Copy
63

Sample Input 3

Copy
271828182845904523
314159265358979323

Sample Output 3

Copy
68833183630578410
题意:给定A,B,问[A,B]里取任意个数按位或,结果有多少种。

思路:这题需要找出一个分界点,即找到最高位的B是1,A是0的位置x(最低位从0开始),那么对于所有OR的结果,x处要么是1要么是0,x是0有多少种呢?这里就需要从[A,1<<x)里挑选数进行OR,即有(1<<x)-A种,因为A到(1<<x)-1都可以表示出来;x处为1有几种呢?有两种情况①从(1<<x, B]里挑选,结果就不说了依此类推,②从上述两个区间都挑选,那就是也是(1<<x)-A种,然后上述两种两种情况可能会有重复,需要判断去重,最后判读是否要加上(1<<x)这一种就行了。

# include <bits/stdc++.h>
using namespace std;
 
typedef long long LL;
int main()
{
    LL i, j, a, b, ans=0;
    scanf("%lld%lld",&a,&b);
    if(a == b)
        return 0*puts("1");
    for(i=60; i>=0; --i)
    {
        if((b>>i&1)^(a>>i&1))
            break;
        if(a>>i&1) a ^= 1LL<<i;
    }
    for(j=i-1; j>=0; --j)
        if(b>>j&1)
        {
            ans += (1LL<<j+1)-1;
            break;
        }
    ans += ((1LL<<i)-a)<<1;
    if(j != -1 && a <= (1LL<<j+1)-1) ans -= (1LL<<j+1)-a;
    printf("%lld\n",ans+(i!=0));
    return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值