D e s c r i p t i o n Description Description
已知一棵 n n n个节点的有根树。有 m m m个询问。每个询问给出了一对节点的编号 x x x和 y y y,询问 x 与 x与 x与 y y y的祖孙关系。
数据范围:对于100%的.据 n , m ≤ 40000 n,m≤40000 n,m≤40000,每个节点的编号都不超过40000。
S o l u t i o n Solution Solution
L C A LCA LCA或 d f s dfs dfs序
C o d e ( L C A ) Code(LCA) Code(LCA)
#include<queue>
#include<cmath>
#include<cstdio>
#include<vector>
#include<cctype>
#include<algorithm>
using namespace std;int n,m,root,x,y,f[40001][17],dep[40001],mdep,t;
vector<int>g[40001];
bool vis[40001];
inline long long read()
{
char c;int d=1;long long f=0;
while(c=getchar(),!isdigit(c))if(c==45)d=-1;f=(f<<3)+(f<<1)+c-48;
while(c=getchar(),isdigit(c)) f=(f<<3)+(f<<1)+c-48;
return d*f;
}
inline void bfs()//求深度
{
queue<int>q;
q.push(root);vis[root]=true;
while(q.size())
{
int x=q.front();q.pop();
for(register int i=0;i<g[x].size();i++)
{
int y=g[x][i];
if(!vis[y])
{
vis[y]=true;
dep[y]=dep[x]+1;
mdep=max(mdep,dep[y]);
f[y][0]=x;
q.push(y);
}
}
}
return;
}
inline int lca(int x,int y)//求x,y的LCA
{
if(dep[x]<dep[y]) swap(x,y);
for(register int i=16;i>=0;i--)
if(dep[x]-(1<<i)>=dep[y]) x=f[x][i];
for(register int i=16;i>=0;i--)
if(f[x][i]!=f[y][i])
{
x=f[x][i];
y=f[y][i];
}
if(x==y) return x;
return f[x][0];
}
signed main()
{
n=read();
for(register int i=1;i<=n;i++)
{
x=read();y=read();
if(y<0) root=x;
else g[x].push_back(y),g[y].push_back(x);
}
bfs();
f[root][0]=-1;
for(register int j=1;j<=floor(log(mdep)/log(2));j++)
for(register int i=1;i<=40000;i++)
if(f[i][j-1]>-1)f[i][j]=f[f[i][j-1]][j-1];else f[i][j]=-1;//预处理
m=read();
while(m--)
{
x=read();y=read();
t=lca(x,y);
if(t!=x&&t!=y) puts("0");
if(t==x) puts("1");
if(t==y) puts("2");
}
}