仓鼠找 sugar
仓鼠找 sugar
LCA
SCUACM2022集训前训练-图论 - Virtual Judge (vjudge.net)
-
首先要观察出一个结论:若 a - b 的路径与 c - d 的路径相交,设 a, b 的 LCA 为 x; c, d 的 LCA 为 y
则有 x 在 c - d 路径上 或 y 在 a - b 路径上
-
如何判断一个点是否在一条路径上:
可观察到一个性质:若 x 在 a,b 路径上,则 \(dist(a,x) + dist(b,x) == dist(a,b)\)
-
求 \(dist(a,b)\): 设 \(t=lca(a,b)\), \(dist(a,b)=depth[a]-depth[t]+depth[b]-depth[t]\)
#include <iostream>
#include <cstring>
#include <algorithm>
#include <vector>
#include <queue>
using namespace std;
typedef long long ll;
const int N = 1e5 + 10, M = 21;
int n, m, Q;
int fa[N][M], depth[N];
vector<vector<int> > G(N);
queue<int> q;
void add(int a, int b)
{
G[a].push_back(b);
}
void bfs(int root)
{
q.push(root);
memset(depth, 0x3f, sizeof depth);
depth[0] = 0;
depth[root] = 1;
while(!q.empty())
{
int t = q.front();
q.pop();
for (auto to : G[t])
{
if (depth[to] != depth[t] - 1)
{
depth[to] = depth[t] + 1;
fa[to][0] = t;
q.push(to);
for (int k = 1; k < M; k++)
fa[to][k] = fa[fa[to][k-1]][k-1];
}
}
}
}
int lca(int a, int b)
{
if (depth[a] < depth[b])
swap(a, b);
for (int k = M-1; k >= 0; k--)
if (depth[fa[a][k]] >= depth[b])
a = fa[a][k];
if (a == b)
return a;
for (int k = M-1; k >= 0; k--)
if (fa[a][k] != fa[b][k])
{
a = fa[a][k];
b = fa[b][k];
}
return fa[a][0];
}
int dist(int a, int b)
{
int t = lca(a, b);
return depth[a] + depth[b] - 2 * depth[t];
}
int main()
{
ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
cin >> n >> Q;
for (int i = 1; i < n; i++)
{
int u, v;
cin >> u >> v;
add(u, v), add(v, u);
}
bfs(1);
while(Q--)
{
int a, b, c, d;
cin >> a >> b >> c >> d;
int x = lca(a, b), y = lca(c, d);
if (dist(x, c) + dist(x, d) == dist(c, d) || dist(y, a) + dist(y, b) == dist(a, b))
cout << "Y" << endl;
else
cout << "N" << endl;
}
return 0;
}