Codeforces 484A Bits

来源:互联网 发布:虚拟服务器和端口转发 编辑:程序博客网 时间:2024/06/05 15:31

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
31 22 41 10
output
137
解题思路:由于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