模板:
cpp
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int MOD = 998244353;
const int N = 2e5 + 10;
int n, m, s, a, b;
vector<int>e[N];
int dep[N], fa[N][20];//深度
//第u个节点向上走2的i次方之后所对应的祖先
void dfs(int u, int father)
{
dep[u] = dep[father] + 1;
fa[u][0] = father;//初始化递归的第一项
for(int i = 1; i <= 19; i ++)
{
fa[u][i] = fa[fa[u][i - 1]][i - 1];
}
for(int v : e[u])
{
if(v != father) dfs(v, u);
}
}
int lca(int u, int v)
{
if(dep[u] < dep[v]) swap(u, v);
//先跳到同一层
for(int i = 19; i >= 0; i --)
{
if(dep[fa[u][i]] >= dep[v])
{
u = fa[u][i];
}//一步一步的跳
}
if(u == v) return v;
for(int i = 19; i >= 0; i --)
{
if(fa[u][i] != fa[v][i])
{
u = fa[u][i], v = fa[v][i];
}
}
return fa[u][0];
}
int main()
{
cin >> n;
while(n --){
cin >> a >> b;
if(b == -1) s = a;
else {
e[a].push_back(b);
e[b].push_back(a);
}
}
dfs(s, 0);
cin >> m;
while(m --){
cin >> a >> b;
int o = lca(a, b);
if(o == a) cout << 1 << endl;
else if(o == b) cout << 2 << endl;
else cout << 0 << endl;
}
return 0;
}