倍增LCA复习
作者:
春江花月夜ovo
,
2024-05-29 13:17:10
,
所有人可见
,
阅读 12
#include <bits/stdc++.h>
#define x first
#define y second
using namespace std;
typedef long long ll;
typedef pair<int, int> PII;
const int N = 4e4 + 10;
vector<int> e[N];
int n, m;
int fa[N][20];
int dep[N];
void bfs(int root)
{
memset(dep, 0x3f, sizeof dep);
dep[0] = 0, dep[root] = 1;
queue<int> q;
q.push(root);
while (!q.empty())
{
auto t = q.front(); q.pop();
for (int i = 0; i < e[t].size(); i ++)
{
int j = e[t][i];
if (dep[j] > dep[t] + 1)
{
q.push(j);
dep[j] = dep[t] + 1;
fa[j][0] = t;
for (int k = 1; k <= 16; k ++)
fa[j][k] = fa[fa[j][k - 1]][k - 1];
}
}
}
}
int LCA(int a, int b)
{
if (dep[a] < dep[b]) swap(a, b);
for (int i = 16; i >= 0; i --)
if (dep[fa[a][i]] >= dep[b])
a = fa[a][i];
if (a == b) return a;
for (int i = 16; i >= 0; i --)
if (fa[a][i] != fa[b][i])
{
a = fa[a][i];
b = fa[b][i];
}
return fa[a][0];
}
int main()
{
ios::sync_with_stdio(false), cin.tie(0);
cin >> n;
int root = -1;
for (int i = 1; i <= n; i ++)
{
int a, b;
cin >> a >> b;
if (b == -1) root = a;
else e[a].push_back(b), e[b].push_back(a);
}
bfs(root);
cin >> m;
for (int i = 1; i <= m; i ++)
{
int a, b;
cin >> a >> b;
int lca = LCA(a, b);
if (lca == a) cout << "1\n";
else if (lca == b) cout << "2\n";
else cout << "0\n";
}
return 0;
}