样例过了,全WA,求调
#include<iostream>
#include<vector>
using namespace std;
int n, q, a, b, c, d;
int x, y;
vector <int > g[500005];
int hig[500005], fa[500005][25];
void dfs(int now, int h, int f)
{
hig[now] = h;
fa[now][0] = f;
for (int i = 1; i <= 20; i++)
fa[now][i] = fa[fa[now][i - 1]][i - 1];
for (auto i : g[now])
if (i != f)
dfs(i, h + 1, now);
}
int lca(int u, int v)
{
if (hig[u] < hig[v])swap(u, v);
for (int i = 20; i >= 0; i--)
{
if (hig[u] - (1 << i) >= hig[v])u = fa[u][i];
}
if (u == v)return u;
else
{
for (int i = 20; i >= 0; i--)if (fa[u][i] != fa[v][i]) u = fa[u][i], v = fa[v][i];
return fa[u][0];
}
}
signed main()
{
cin >> n >> q;
for (int i = 1; i < n; i++)
{
cin >> x >> y;
g[x].push_back(y);
g[y].push_back(x);
}
dfs(1, 0, 0);
while (q--)
{
cin >> a >> b >> c >> d;
int x = lca(a, b), y = lca(c, d);
int l1 = lca(a, c), l2 = lca(b, d);
if (abs(hig[l1] - hig[a]) + abs(hig[l1] - hig[c]) + abs(hig[l1] - hig[b]) + abs(hig[l1] - hig[d]) <= abs(hig[x] - hig[a]) + abs(hig[x] - hig[b]) + abs(hig[y] - hig[c]) + abs(hig[l1] - hig[d]))cout << "Y \n";
else cout << "N \n";
}
}