图论---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
*/
相关推荐
happygrilclh20 小时前
高压高频电源的pid算法
算法
格林威20 小时前
Baumer相机铸件气孔与缩松识别:提升铸造良品率的 6 个核心算法,附 OpenCV+Halcon 实战代码!
人工智能·opencv·算法·安全·计算机视觉·堡盟相机·baumer相机
你好!蒋韦杰-(烟雨平生)20 小时前
OpenGL
c++·数学·游戏·3d
葫三生20 小时前
存在之思:三生原理与现象学对话可能?
数据库·人工智能·神经网络·算法·区块链
郁闷的网纹蟒20 小时前
虚幻5---第12部分---蒙太奇
开发语言·c++·ue5·游戏引擎·虚幻
Evand J20 小时前
【MATLAB例程】无人机三维路径规划|A*,RRT(快速随机树算法), APF(人工势场法)算法对比|可自定义起终点、障碍物坐标。附下载链接
算法·matlab·无人机·astar·路径规划·rrt·apf
嵌入小生00720 小时前
双向链表、双向循环链表之间的异同---嵌入式入门---Linux
linux·c语言·数据结构·链表·嵌入式·小白
少许极端20 小时前
算法奇妙屋(二十七)-全排列与子集问题
算法·剪枝·回溯·递归
sali-tec20 小时前
C# 基于OpenCv的视觉工作流-章20-仿射变换
图像处理·人工智能·opencv·算法·计算机视觉
u01092727120 小时前
实时数据流处理
开发语言·c++·算法