Codeforces Global Round 13 D. Zookeeper and The Infinite Zoo(思维,位运算)

题目描述

There is a new attraction in Singapore Zoo: The Infinite Zoo.
The Infinite Zoo can be represented by a graph with an infinite number of vertices labeled 1,2,3,…. There is a directed edge from vertex u to vertex u+v if and only if u&v=v, where & denotes the bitwise AND operation. There are no other edges in the graph.
Zookeeper has q queries. In the i-th query she will ask you if she can travel from vertex ui to vertex vi by going through directed edges.

Input

The first line contains an integer q (1≤q≤105) — the number of queries.
The i-th of the next q lines will contain two integers ui, vi (1≤ui,vi<230) — a query made by Zookeeper.

Output

For the i-th of the q queries, output “YES” in a single line if Zookeeper can travel from vertex ui to vertex vi. Otherwise, output “NO”.
You can print your answer in any case. For example, if the answer is “YES”, then the output “Yes” or “yeS” will also be considered as correct answer.

Example

input
5
1 4
3 6
1 6
6 2
5 5
output
YES
YES
NO
NO
YES

Note

The subgraph on vertices 1,2,3,4,5,6 is shown below.
在这里插入图片描述

题目描述

有一个序列1,2,3,……,正无穷。u可以到u+v当且仅当u&v=v。有q个查询,每个查询给出两个点u和v,问u是否能到v。

题目分析

首先我们可以确定,如果u能到v,那么v一定大于u。因为所有边都是 u − > u + 某 个 数 u->u+某个数 u>u+ 得到的。条件1:v>=u

然后我们分析一下每个点之间的联通条件。
以3为例,3可以到3+1、3+2和3+3。我们可以发现:一个数(二进制)的所有1的位置都可以向左移动,但是不能够向右移动
条件2:u和v(二进制)的1从右向左进行一一对应,如果u中的所有1所对应的v中的1,全部都大于u中对应的1的话,那么u可以到v。
举例:6(110)可以到达6+2,6+4和6+6。但是6到不了7(111)和9(1001)。

代码如下
#include <iostream>
#include <cstdio>
#include <cmath>
#include <string>
#include <cstring>
#include <map>
#include <unordered_map>
#include <queue>
#include <vector>
#include <set>
#include <bitset>
#include <algorithm>
#define LL long long
#define PII pair<int,int>
#define x first
#define y second
using namespace std;
const int N=1e4+5,mod=1e9+7;
bool check(int u,int v)
{
	int a=0,b=0;					//a记录u中当前未匹配的个数,b记录v中当前未匹配的个数
	for(int i=0;i<31;i++)
	{
		if(u>>i&1) a++;				//如果当前位上有1,那么进行记录
		if(v>>i&1) b++;
		if(b)						//如果b中有元素了
		{
			if(!a) return false;	//但是a中还没有元素,那么说明与当前位匹配的u中的1要大于该位,不合法
			a--,b--;				//否则匹配成功
		}
	}
	return true;
}
int main()
{
	int q;
	scanf("%d",&q);
	while(q--)
	{
		int u,v;
		scanf("%d%d",&u,&v);
		
		if(u<=v&&check(u,v)) puts("YES");		//利用条件1,2进行匹配
		else puts("NO");
	}
	return 0;
}
  • 6
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 10
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lwz_159

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值