图论---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
*/
相关推荐
我爱计算机视觉21 分钟前
ICCV 2025 (Highlight) Being-VL:师夷长技,用NLP的BPE算法统一视觉语言模型
人工智能·算法·语言模型·自然语言处理
Vect__1 小时前
从直线到环形:解锁栈、队列背后的空间与效率平衡术
数据结构·c++
头发还没掉光光3 小时前
C++STL之list
c语言·数据结构·c++·list
我笑了OvO5 小时前
C++类和对象(1)
java·开发语言·c++·类和对象
virtual_k1smet6 小时前
#等价于e * d ≡ 1 mod φ(n) #模逆元详解
人工智能·算法·机器学习
可触的未来,发芽的智生6 小时前
新奇特:神经网络的集团作战思维,权重共享层的智慧
人工智能·python·神经网络·算法·架构
_屈臣_6 小时前
卡特兰数【模板】(四个公式模板)
c++·算法
渡我白衣7 小时前
C++ 异常处理全解析:从语法到设计哲学
开发语言·c++·面试
坚持编程的菜鸟7 小时前
LeetCode每日一题——交替合并字符串
c语言·算法·leetcode
青草地溪水旁7 小时前
设计模式(C++)详解——观察者模式(Observer)(1)
c++·观察者模式·设计模式