CodeForces - 484A Codeforces Round #276 (Div. 1) A题

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.


题意为在[l,r]区间里找到一个最小的数,这个数的转化为二进制1的个数最多;

可以这样考虑,一个数 10010010 要找到比它小,但是二进制1多的数,可以贪心的把1变成0,然后把这个 1 后面的 0 变成 1 ;

例如变成:01111111,10001111,10010001;

最后判断一下就行,特别注意(1<<i)当i大于31时,也就是说当超过 int 型时,会爆,可以把1改为1ll;

代码:

#include<bits/stdc++.h>
#define ll long long
#define pa pair<int,int>
#define lson k<<1
#define rson k<<1|1
#define inf 0x3f3f3f3f
//ios::sync_with_stdio(false);
using namespace std;
const int N=100100;
const int M=1000100;
const ll mod=1e9+7;
vector<int>ve;//1的位置
void solve(ll p){
	int cnt=0;
	while(p){
		cnt++;
		if(p%2) ve.push_back(cnt);
		p/=2;
	}
}
int main(){
    ios::sync_with_stdio(false);
    int n;
    cin>>n;
    while(n--){
    	ve.clear();
    	ll l,r;
    	cin>>l>>r;
    	solve(r);
    	ll ans=r;//最小答案
		int ms=ve.size();//1的个数
		for(int i=ve.size()-1;i>=0;i--){
			int b=ve[i]-1;
			ll a=(1ll<<(ve[i]-1))-1;
			for(int j=i+1;j<ve.size();j++){
				a+=(1ll<<(ve[j]-1));
				b++;
			}
			if(a>=l&&b>ms) ms=b,ans=a;
			else if(a>=l&&b==ms&&a<ans) ans=a;
		}
		cout<<ans<<endl;
	}
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值