Let's denote as the number of bits set ('1' bits) in the binary representation of the non-negative integerx.
You are given multiple queries consisting of pairs of integers l and r. For each query, find thex, such thatl ≤ 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 integersli, ri — the arguments for the corresponding query (0 ≤ li ≤ ri ≤ 1018).
Output
For each query print the answer in a separate line.
题目大意:
在范围[a,b]中寻找二进制位1最多的最小数
解题思路:
假设开始二进制每一位都为1,从高位i开始枚举,如果当前数大于b,且减去1<<i后仍大于等于a,就减1<<i,直到当前数在[a,b]之间时,输出当前数(由于是从高位开始减,所以当前数是最小的)
代码:
#include<iostream> #include<map> #include<cstring> #include<cstdlib> #include<cmath> #include<algorithm> #include<cstdio> using namespace std; typedef long long LL;; LL bit[65]; int main() { bit[0] = 1; for(int i = 1; i <= 60; i++) bit[i] = bit[i-1] << 1; int n; scanf("%d", &n); LL a, b, ans; while(n--) { scanf("%lld %lld", &a, &b); ans = (1LL << 61) - 1; for(int i = 60; i >= 0; i--) { if(ans > b && ans - bit[i] >= a) ans -= bit[i]; if(ans >= a && ans <= b) break; } cout << ans << endl; } return 0; }