跳到正文

个人记录

算法模版__树论

Eclatara约 2 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2026年6月2日
篇幅
约 2 分钟

版本

  1. v1当前

LCA

C++
#include<bits/stdc++.h>
#define int long long
using namespace std;
const int N=1e6+10;
vector<int> g[N];
int dep[N],top[N],wc[N],size[N],f[N],n,m,r;
void dfs1(int u,int fa){
	f[u]=fa;
	size[u]=1;
	dep[u]=dep[fa]+1;
	for(auto v:g[u]){
		if(v==fa) continue;
		dfs1(v,u);
		size[u]+=size[v];
		if(size[v]>size[wc[u]]) wc[u]=v;
	}
}
void dfs2(int u,int fa){
	top[u]=fa;
	if(!wc[u]) return;
	dfs2(wc[u],fa);
	for(auto v:g[u])
		if(v!=f[u]&&v!=wc[u]) dfs2(v,v);
}
int lca(int x,int y){
	while(top[x]!=top[y]){
		if(dep[top[x]]<dep[top[y]]) swap(x,y);
		x=f[top[x]];
	}
	return (dep[x]<dep[y])?x:y;
}
signed main(){
	ios::sync_with_stdio();
	cin.tie(),cout.tie();
	cin>>n>>m>>r;
	for(int i=1;i<n;i++){
		int u,v;
		cin>>u>>v;
		g[u].push_back(v);
		g[v].push_back(u);
	}
	dfs1(r,0);
	dfs2(r,0);
	for(int i=1;i<=m;i++){
		int x,y;
		cin>>x>>y;
		cout<<lca(x,y)<<"\n";
	}
}
原文