Codeforces Round #276 (Div. 2)-C. Bits

原题链接

C. Bits
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output

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.

Examples
input
3
1 2
2 4
1 10
output
1
3
7
Note

The binary representations of numbers from 1 to 10 are listed below:

110 = 12

210 = 102

310 = 112

410 = 1002

510 = 1012

610 = 1102

710 = 1112

810 = 10002

910 = 10012

1010 = 10102



1.若l == r 或者r == 2 ^ n - 1则直接输出r

2.把l和r化为二进制存在数组s1, s2里,从高位开始遍历s2数组,若存在s2[i] == 1 && s1[i] == 0,此时判断s2中0..i-1是否全为一,若全为1则直接俄输出s2,若不全为1,则把s2[i] = 0, 并且把s2中1..i-1变为1在算出s2输出.

 

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>

using namespace std;
typedef long long ll;

int s1[100], s2[100];
int solve(ll p, int *s){
	
	int k = 0;
	while(p){
		s[k++] = p % 2;
		p /= 2;
	}
	return k;
}
int main(){
	
//	freopen("in.txt", "r", stdin);
	int n;
	
	scanf("%d", &n);
	while(n--){
		
		memset(s1, 0, sizeof(s1));
		memset(s2, 0, sizeof(s2));
		ll l, r;
		
		scanf("%I64d%I64d", &l, &r);
		if(l == r){
			printf("%I64d\n", r);
			continue;
		}
		int sign = 0;
	    int len1 = solve(l, s1);
	    int len2 = solve(r, s2);
	    for(int i = 0; i < len2; i++){
	    	if(s2[i] == 0){
	    		sign = 1;
	    		break;
			}
		}
		if(sign == 0){
			printf("%I64d\n", r);
			continue;
		}
		for(int i = len2 - 1; i >= 0; i--){
			if(s2[i] == 1 && s1[i] == 0){
				sign = 0;
				for(int k = i-1; k >= 0; k--)
				 if(s2[k] == 0){
				 	sign = 1;
				 	break;
				 }
				if(sign == 0)
				   break;
				for(int j = i-1; j >= 0; j--)
				 s2[j] = 1;
				s2[i] = 0;
				break;
			}
		}
		ll p = 0;
		for(int i = len2 - 1; i >= 0; i--){
			p = p * 2 + s2[i];
		}
		printf("%I64d\n", p);
	}
	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值