HDU5969-最大的位或

216 篇文章 0 订阅

最大的位或

                                                                     Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)
                                                                                             Total Submission(s): 1414    Accepted Submission(s): 558


Problem Description
B君和G君聊天的时候想到了如下的问题。
给定自然数l和r ,选取2个整数x,y满足l <= x <= y <= r ,使得x|y最大。
其中|表示按位或,即C、 C++、 Java中的|运算。
 

Input
包含至多10001组测试数据。
第一行有一个正整数,表示数据的组数。
接下来每一行表示一组数据,包含两个整数l,r。
保证 0 <= l <= r <=  1018
 

Output
对于每组数据输出一行,表示最大的位或。
 

Sample Input
  
  
5 1 10 0 1 1023 1024 233 322 1000000000000000000 1000000000000000000
 

Sample Output
  
  
15 1 2047 511 1000000000000000000
 

Source
 

Recommend
jiangzijing2015
 

解题思路:可以先把r转化为二进制,设位数为x,如果l<=(1<<(x-1))-1,那么最大就为r|((1<<(x-1))-1),否则的话l和r的位数必然一样,那么不断地把l和r除以二直至两数相等,记录下有多少位不同,设为y,那么构造出(1<<y)-1和r做或操作即是答案



#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <cmath>

using namespace std;

#define LL long long
const int INF = 0x3f3f3f3f;

int main()
{
	LL l, r;
	int T;
	scanf("%d", &T);
	while (T--)
	{
		scanf("%lld%lld", &l, &r);
		LL x = r;
		int cnt = 0;
		while (x>0)
		{
			cnt++;
			x /= 2;
		}
		LL y = cnt ? (1LL << (cnt - 1)) - 1 : 0;
		if (y >= l) printf("%lld\n", r | y);
		else
		{
			LL xx = l, yy = r;
			int cnt = 0;
			while (xx != yy)
			{
				xx >>= 1, yy >>= 1;
				cnt++;
			}
			LL zz = (1LL <<cnt) - 1;
			printf("%lld\n", r | zz);
		}
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值