题目描述
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;
}
转载:https://blog.csdn.net/li_wen_zhuo/article/details/114247335