codeforces 484a//Bits// Codeforces Round #276(Div. 1)

本文介绍了一种算法,用于找出指定区间内二进制表示中1的数量最多的整数。通过比较区间的二进制表示,确定目标数值的二进制结构,并给出具体的实现代码。

题意:给出区间[ll,rr],求中间一个数二进制表示时一的个数最多。

写出ll和rr的二进制,设出现第一个不同的位置为pos(从高位到低位),找的数为x,那么为了使x在[ll,rr]内,前pos-1个位必须也相同。而rr在pos和pos后如果都为1,那么pos和pos后都取1,否则pos取0,pos后取1。

乱码:

//#pragma comment(linker,"/STACK:1024000000,1024000000") 
#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<vector>
#include<cmath>
#include<queue>
#include<stack>
#include<map>
#include<set>
#include<algorithm>
#include <stack>
#include <list>
using namespace std;
const int SZ=1000010,INF=0x7FFFFFFF;
typedef long long lon;
const double EPS=1e-9;
const lon one=1;

lon geth(lon x)
{
    lon res=0;
    for(lon i=0;i<64;++i)
    {
        if(x&(one<<i))
        {
            res=max(res,i);
        }
    }
    return res;
} 

int main()
{
    std::ios::sync_with_stdio(0);
    //freopen("d:\\1.txt","r",stdin); 
    lon n;
    cin>>n;
    for(int i=0;i<n;++i)
    {
        lon ll,rr;
        cin>>ll>>rr;
        lon bit=geth(rr);
        lon res=0;
        for(lon j=bit;j>=0;--j)
        {
            lon b1=rr&(one<<j);
            lon b2=ll&(one<<j);
            if(b1^b2)
            {
                lon cand=0;
                for(lon k=j;k>=0;--k)
                {
                    if(rr&(one<<k))++cand;
                }
                res+=(one<<max(j,cand))-1;
                break;
            }
            else res+=((one<<j)&rr);
        }
        cout<<res<<endl;
    }
    
    return 0;
}

 

转载于:https://www.cnblogs.com/gaudar/p/9664807.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值