Codeforces Global Round 13 D. Zookeeper and The Infinite Zoo (thinking, bit operations)

Title description

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.
Insert picture description here

Title description

There is a sequence 1, 2, 3,..., positive infinity. u can go to u+v if and only if u&v=v. There are q queries, each query gives two points u and v, and asks whether u can reach v.

Topic analysis

First of all, we can determine that if u can reach v, then v must be greater than u . Because all edges are u −> u + some number u->u+ some numberu ->u+A one number get.条件1:v>=u

Then we analyze the connection conditions between each point.
Taking 3 as an example, 3 can reach 3+1, 3+2, and 3+3. We can find that all 1 positions of a number (binary) can be moved to the left, but not to the right .
条件2:u和v(二进制)的1从右向左进行一一对应,如果u中的所有1所对应的v中的1,全部都大于u中对应的1的话,那么u可以到v。
Example: 6(110) can reach 6+2, 6+4 and 6+6. But 6 can't reach 7(111) and 9(1001).

code show as below
#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;
}

Guess you like

Origin blog.csdn.net/li_wen_zhuo/article/details/114247335