图论---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
*/
相关推荐
TU^1 分钟前
C语言习题~day27
c语言·数据结构·算法
2401_841495649 分钟前
【自然语言处理】Transformer模型
人工智能·python·深度学习·算法·语言模型·自然语言处理·transformer
m0_748233649 分钟前
C++与Python:内存管理与指针的对比
java·c++·python
孤廖10 分钟前
面试官问 Linux 编译调试?gcc 编译流程 + gdb 断点调试 + git 版本控制,连 Makefile 都标好了
linux·服务器·c++·人工智能·git·算法·github
终焉代码17 分钟前
【Linux】进程初阶(1)——基本进程理解
linux·运维·服务器·c++·学习·1024程序员节
我想吃余17 分钟前
Linux进程间通信:管道与System V IPC的全解析
linux·服务器·c++
紫荆鱼18 分钟前
设计模式-备忘录模式(Memento)
c++·后端·设计模式·备忘录模式
Wind哥28 分钟前
VS Code搭建C/C++开发调试环境-Windows
c语言·开发语言·c++·visual studio code
404未精通的狗1 小时前
(数据结构)栈和队列
android·数据结构
Zero不爱吃饭1 小时前
将有序数组转换为二叉搜索树
数据结构·算法