图论---LCA(倍增法)

预处理 O( n logn ),查询O( log n )

cpp 复制代码
#include<bits/stdc++.h>
using namespace std;
typedef pair<int,int> pii;
const int N=40010,M=2*N;//是无向边,边需要见两边

int n,m;
vector<int> g[N];
//2的幂次范围 0~15
int depth[N],fa[N][15];
void bfs(int root){
	memset(depth,0x3f,sizeof depth);
	depth[0]=0,depth[root]=1;
	queue<int> q;
	q.push(root);
	while(q.size()){
		int t=q.front();
		q.pop();
		for(auto x:g[t]){
			if(depth[x]>depth[t]+1){
				depth[x]=depth[t]+1;
				q.push(x);
				fa[x][0]=t;
				for(int k=1;k<=15;++k){
					fa[x][k]=fa[fa[x][k-1]][k-1];
				}
			}
		}
	}
}
int lca(int a,int b){
	if(depth[a]<depth[b]) swap(a,b);
	for(int k=15;k>=0;--k){
		if(depth[fa[a][k]]>=depth[b]){
			a=fa[a][k];
		}
	}
	if(a==b) return a;
	for(int k=15;k>=0;--k){
		if(fa[a][k]!=fa[b][k]){
			a=fa[a][k];
			b=fa[b][k];
		}
	}
	return fa[a][0];
}
int main(){
	scanf("%d",&n);
	int root=0;
	for(int i=0;i<n;++i){
		int a,b;
		cin>>a>>b;
		if(b==-1) root=a;
		g[a].push_back(b),g[b].push_back(a);
	}
	bfs(root);
	scanf("%d",&m);
	while(m--){
		int a,b;
		cin>>a>>b;
		int p=lca(a,b);
		if(p==a) puts("1");
		else if(p==b) puts("2");
		else puts("0");
	}
}
/*
10
234 -1
12 234
13 234
14 234
15 234
16 234
17 234
18 234
19 234
233 19
5
234 233
1
233 12
0
233 13
0
233 15
0
233 19
2
*/
相关推荐
hu_yuchen1 小时前
C++:Lambda表达式
开发语言·c++·算法
烨然若神人~1 小时前
算法训练营第五天 | 454.四数相加II\ 383. 赎金信\15. 三数之和\ 18. 四数之和
算法
一只鱼^_1 小时前
牛客周赛 Round 91
数据结构·c++·算法·数学建模·面试·贪心算法·动态规划
啊阿狸不会拉杆1 小时前
人工智能数学基础(三):微积分初步
人工智能·python·算法·数学建模
2401_858286112 小时前
CC52.【C++ Cont】滑动窗口
开发语言·数据结构·c++·算法·leetcode·滑动窗口
mvufi3 小时前
day31 第八章 贪心算法 part05
算法·贪心算法
珊瑚里的鱼3 小时前
第一讲 | 算法复杂度
c语言·开发语言·数据结构·笔记·算法·visualstudio·visual studio
啊阿狸不会拉杆3 小时前
人工智能数学基础(四):线性代数
人工智能·python·数学·算法·机器学习
OSwich4 小时前
【虚幻C++笔记】碰撞检测
c++·笔记·虚幻
玖剹4 小时前
矩阵区域和 --- 前缀和
数据结构·c++·算法·leetcode·矩阵·动态规划·1024程序员节