AcWing 1172. 祖孙询问
原题链接
中等
作者:
最后五分钟
,
2024-03-24 13:47:33
,
所有人可见
,
阅读 5
#include<bits/stdc++.h>
#define LL long long
#define x first
#define y second
#define de(x) cout<<#x<<" = "<<x<<" "
#define deg(x) cout<<#x<<" = "<<x<<endl
using namespace std;
const int N=4e4+10,M=2*N;
typedef pair<int,int> PII;
int h[N],e[M],ne[M],idx;
int depth[N],f[N][20];
int root;
void add(int a,int b)
{
e[idx]=b,ne[idx]=h[a],h[a]=idx++;
}
void bfs()
{
queue<int> q;
q.push(root);
depth[0]=0,depth[root]=1;
while(q.size())
{
int t=q.front();
q.pop();
for(int i=h[t];~i;i=ne[i])
{
int j=e[i];
if(depth[j]>depth[t]+1)
{
depth[j]=depth[t]+1;
f[j][0]=t;
q.push(j);
for(int k=1;k<=19;k++)
{
int anc=f[j][k-1];
f[j][k]=f[anc][k-1];
}
}
}
}
}
int lca(int a,int b)
{
if(depth[a]<depth[b])swap(a,b);
for(int k=19;k>=0;k--)
if(depth[f[a][k]]>=depth[b])a=f[a][k];
if(a==b)return a;
for(int k=19;k>=0;k--)
if(depth[f[a][k]]!=depth[f[b][k]])
{
a=f[a][k];
b=f[b][k];
}
return f[a][0];
}
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int n;
cin>>n;
memset(h,-1,sizeof h);
memset(depth,0x3f,sizeof depth);
for(int i=1;i<=n;i++)
{
int a,b;
cin>>a>>b;
if(b==-1)
{
root=a;
continue;
}
add(a,b);
add(b,a);
}
bfs();
int m;
cin>>m;
for(int i=1;i<=m;i++)
{
int a,b;
cin>>a>>b;
int p=lca(a,b);
if(p==a)cout<<1<<endl;
else if(p==b)cout<<2<<endl;
else cout<<0<<endl;
}
return 0;
}
AcWing《CCF-CSP认证辅导课》拼团优惠!https://www.acwing.com/activity/content/introduction/39/group_buy/205418/