如果两条路径相交,那么一定有一条路径的LCA在另一条路径上
而判断一个节点x,是否在路径s-t上需要满足如下几个条件
- deep[x]>=deep[LCA(s,t)]
- LCA(s,x)=x或LCA(t,x)=x;
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<queue>
#include<vector>
#include<stdlib.h>
#include <math.h>
#define LL long long
using namespace std;
const int maxn = 5e5 + 10;
int n, m, s;
int k = 0;
int head[maxn], de[maxn], Fa[maxn][21];//de表示节点深度,Fa表示该节点的2的x次方的父节点
int tot = 0;
struct node {
int nxt;
int to;
}e[maxn*2];
inline void add(int u, int v) {
e[++tot].to = v;
e[tot].nxt = head[u];
head[u] = tot;
}
inline void dfs(int u, int fa) {
de[u] = de[fa] + 1;
Fa[u][0] = fa;
for (int i = 1; (1 << i) <= de[u]; i++) {
Fa[u][i] = Fa[Fa[u][i - 1]][i - 1];
}
for (int i = head[u], v; i != -1; i = e[i].nxt) {
v = e[i].to;
if (v != fa) {
dfs( v,u );
}
}
}
int lca(int a, int b) {
if (de[a] > de[b]) {
swap(a, b);
}
for (int i = 20; i >= 0; i--) {
if (de[a] <= de[b]-(1<<i)) {
b = Fa[b][i];
}
}
if (a == b) return a;
for (int i = 20; i >= 0; i--) {
if (Fa[a][i] == Fa[b][i]) {
continue;
}
else {
a = Fa[a][i];
b = Fa[b][i];
}
}
return Fa[a][0];
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
memset(head, -1, sizeof(head));
cin >> n >> m;
for (int i = 1,x,y; i < n; i++) {
cin >> x >> y;
add(x, y);
add(y, x);
}
dfs(1, 0);
for (int i = 1,a,b,c,d; i <= m; i++) {
cin >> a >> b >> c >> d;
int s = lca(a, b); int t = lca(c, d);
if (de[s] > de[t]) {
if (lca(c, s) == s || lca(s, d) == s) {
cout << 'Y' << endl;
}
else cout << 'N' << endl;
}
else {
if (lca(a, t) == t || lca(t, b) == t) {
cout << 'Y' << endl;
}
else cout << 'N' << endl;
}
}
}