# [题解] Luogu – 3398 仓鼠找sugar

## 样例输入

5 5
2 5
4 2
1 3
1 4
5 1 5 1
2 2 1 4
4 1 3 4
3 1 1 5
3 5 1 4


## 样例输出

Y
N
Y
Y
Y


## 解题思路

$deep_x \geq deep_c$
$lca(a, x) = x$ 或 $lca(b,x) = x$

## 代码

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>

using namespace std;
const int MAXN = 100000 + 10;
const int MAXM = 200000 + 10;

int Head[MAXN], to[MAXM], Next[MAXM], tot = 1;

inline void add(int a, int b){
to[tot] = b;
}

int x = 0;
char ch = getchar();

while(ch < '0' || ch > '9')
ch = getchar();

while('0' <= ch && ch <= '9'){
x = x*10 + ch - '0';
ch = getchar();
}

return x;
}

int f[MAXN][20], deep[MAXN];

inline void dfs(int x, int fa){
for(register int i=1; i<=17; i++){
f[x][i] = f[f[x][i-1]][i-1];
}

for(register int i=Head[x]; i; i=Next[i]){
int v = to[i];
if(v != fa){
f[v][0] = x;
deep[v] = deep[x] + 1;

dfs(v, x);
}
}
}

inline int LCA(int a, int b){
if(deep[a] < deep[b]){
swap(a, b);
}

for(register int i=17; i>=0; i--){
if(deep[f[a][i]] >= deep[b]){
a = f[a][i];
}
}

if(a == b)
return a;

for(register int i=17; i>=0; i--){
if(f[a][i] != f[b][i]){
a = f[a][i];
b = f[b][i];
}
}

return f[a][0];
}

int n, q;

int main(){

for(register int i=0; i<n-1; i++){
int a = read();
int b = read();

}

deep[1] = 1;
dfs(1, 0);

for(register int i=0; i<q; i++){
int a = read();
int b = read();
int c = read();
int d = read();

int x = LCA(a, b);
int y = LCA(c, d);

if(deep[x] < deep[y]){
swap(x, y);
swap(a, c);
swap(b, d);
}

if(LCA(x, c) == x || LCA(x, d) == x){
printf("Y\n");
}else{
printf("N\n");
}
}
return 0;
}