Codeforces 484A Bits

Let's denote as  the number of bits set ('1' bits) in the binary representation of the non-negative integer x.

You are given multiple queries consisting of pairs of integers l and r. For each query, find the x, such that l ≤ x ≤ r, and is maximum possible. If there are multiple such numbers find the smallest of them.

Input

The first line contains integer n — the number of queries (1 ≤ n ≤ 10000).

Each of the following n lines contain two integers li, ri — the arguments for the corresponding query (0 ≤ li ≤ ri ≤ 1018).

Output

For each query print the answer in a separate line.

Sample test(s)
input
3
1 2
2 4
1 10
output
1
3
7
 
   
解题思路:由于l和r的范围很大,因此本题我们需要按位处理,二进制表示设置为60位。
求解[l,r)范围内的某一个元素使得其二进制表示中1的个数最多,首先将l和r表示成二进制形式,按照二进制位从高到低的顺序找出第一个r的表示为1,l的表示为0的位置,则答案便是当前位设置为0,后面的位全部设置为1,这样在满足区间范围的情况下二进制表示中1的个数是最多的,将这个结果和r进行比较,综合得出最优值。
 
   
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <string>
#include <algorithm>
#include <functional>
using namespace std;
typedef long long ll;
int n;
ll  l, r;
int a[110], b[110], c[110];

int count_bit(ll x) {
    int res = 0;
    while(x) {
        if(x&1) res++;
        x >>= 1;
    }
    return res;
}

int main() {

	cin >> n;
	while(n--) {
		cin >> l >> r;
		memset(a, 0, sizeof(a));
		memset(b, 0, sizeof(b));
		for(int i = 0; i <= 60; ++i) {
			a[i] = ((1LL<<i)&l) > 0;
			b[i] = ((1LL<<i)&r) > 0;
		}
		ll ans = 0;
		for(int i = 60; i >= 0; --i) {
            if(a[i]^b[i]) {
                ans = (ans<<1)|a[i];
                ans = (ans<<i)|((1LL<<i)-1);
                break;
            } else {
                ans = (ans<<1)|b[i];
            }
		}
		if(count_bit(ans) < count_bit(r)) {
            ans = r;
		}
		cout << ans << endl;
	}
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值