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
- codeforces 484a Bits
- codeforces 484 A-Bits
- CodeForces 484A Bits
- codeforces-484A Bits
- Codeforces 484A Bits
- codeforces 484A bits
- Codeforces-484A-Bits
- Bits - CodeForces 484 A 水题
- codeforces 484A Bits 数论
- Codeforces 484A Bits(贪心)
- Codeforces 484A - Bits (贪心)
- Codeforces 484A. Bits 贪心
- codeforces 484A Bits 贪心->位数
- [Codeforces 484A]Bits(拆位贪心)
- Review of codeforces 484A Bits based on python
- A. Bits(Codeforces Round #276(div1)
- Codeforces Round #276 (Div. 1) A. Bits
- Codeforces Round #276 (Div. 1) A. Bits
- HDOJ 1203 I NEED A OFFER!(01背包)
- 1030. Travel Plan (30)
- xib 加载另一个 xib的各个场景
- i686只是cpu的指令等级,包括32bit和64bit
- 数据结构------树
- Codeforces 484A Bits
- 华为oj: 字符串最后一个单词的长度
- sql注入过程详解(二)
- BaseSpider在scrapy中的使用
- iOS 之 UITableView 使用索引
- 【Java基础】--深入剖析基础语法
- CF571C-CNF 2
- java进程 线程分析
- [python] UDP客户端/服务器端