祖孙询问

题目链接
思路:如果x是最近公共祖先,输出1
如果y是最近公共祖先,输出2
其他 0

#include<bits/stdc++.h>
using namespace std;

const int N=4e4+10;
const int maxbit=20;
vector<int> G[N];
int dep[N];
int father[N][maxbit];
int lg[N];
int n,m,x,y,root;
void dfs(int now,int fa){
	dep[now]=dep[fa]+1;
	father[now][0]=fa;
	for(int i=1;i<=lg[dep[now]]+1;i++){
		father[now][i]=father[father[now][i-1]][i-1];
	}
	for(int i=0;i<G[now].size();i++){
		if(G[now][i]!=fa){
			dfs(G[now][i],now);
		}
	}
}
int lca(int u,int v){
	if(dep[u]<dep[v]) swap(u,v);
	while(dep[u]!=dep[v]){
		u=father[u][lg[dep[u]-dep[v]]];
	}
	if(u==v) return u;
	for(int i=lg[dep[u]];i>=0;i--){
		if(father[u][i]!=father[v][i]){
			u=father[u][i];
			v=father[v][i];
		}
	}
	return father[u][0];
}
int main(){
	lg[0]=-1;
	for(int i=1;i<N;i++){
		lg[i]=lg[i>>1]+1;
	}
	cin>>n;
	for(int i=0;i<n;i++){
		cin>>x>>y;
		if(y==-1) root=x;
		else{
			G[x].push_back(y);
			G[y].push_back(x);
		}
	}
	dfs(root,0);
	cin>>m;
	for(int i=0;i<m;i++){
		cin>>x>>y;
		int LCA=lca(x,y);
		if(LCA==x) cout<<1<<endl;
		else if(LCA==y) cout<<2<<endl;
		else cout<<0<<endl;
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值