跳到正文

个人记录

最近公共祖先(LCA)

Hhy140516约 13 分钟
原文
文章信息与版本

文章信息

发布
2025年3月23日
收录
2025年12月12日
更新
2026年11月5日
篇幅
约 13 分钟

版本

  1. v1当前

定义

对于树上两个节点 xx 和 yy,xx 和 yy 的祖先节点中,共同的且深度最大的节点,称之为 xx 和 yy 的 lca。

求解

法一:暴力

从 xx 点出发向上到根节点,并沿途标记所有点。yy 再次向上尝试走到根节点,yy 遇到的第一个已经标记的点即为 lca(x , y)。时间 O(n)O(n)

法二:倍增

第一部分:预处理

  1. depidep_i 表示点 ii 的深度。
  2. dpi,jdp_{i,j} 表示点 ii 移动 2j2 ^ j 后到的点数。

第二部分:处理询问

  1. 约定深度较大的点,确定研究对象。
  2. 将 yy 倍增移动到与 xx 深度相同。
  3. 将 xx 和 yy 一起向上倍增移动,但不重合。

代码

C++
void dfs(int u , int fa)
{
	dep[u] = dep[fa] + 1 ;
	dp[u][0] = fa ;
	for( int i = 1 ; (1 << i) <= dep[u] ; i++ )
	{
		dp[u][i] = dp[dp[u][i - 1]][i - 1] ;
	}
	for( int i = 0 ; i < G[u].size() ; i++ )
	{
		int v = G[u][i] ;
		if(v == fa) continue ;
		dfs(v , u) ;
	}
}
int lca(int x , int y)
{
	if(dep[x] > dep[y]) swap(x , y) ;
	for( int i = 20 ; i >= 0 ; i-- )
	{
		if(dep[dp[y][i]] >= dep[x]) y = dp[y][i] ;
	}
	if(x == y) return y ;
	for( int i = 20 ; i >= 0 ; i-- )
	{
		if(dp[x][i] != dp[y][i]) y = dp[y][i] , x = dp[x][i] ;
	}
	return dp[x][0] ;
}

模版

P3379

模版。

C++
//Code by hhy
#include<bits/stdc++.h>
#define F(i , a , b , c) for( int i = (a) ; ((c > 0) ? i <= (b) : i >= (b)) ; i += c )
#define T(i , root , b , c) for( int i = root ; b ; c )
#define int long long
#define W(f) while(f)
#define ull unsigned long long
#define pb push_back
#define fi first
#define se second
#define ll long long
#define debug(...){\
	cout<<"debug in function "<<__FUNCTION__<<",line "<<__LINE__<<"\n";\
	string s=#__VA_ARGS__,s2="";\
	vector<string>v;\
	for(auto i:s){\
		if(i==','){\
			v.push_back(s2);\
			s2="";\
		}else{\
			s2+=i;\
		}\
	}\
	v.push_back(s2);\
	vector<int>v2={__VA_ARGS__};\
	for(int i=0;i<v.size()-1;i++){\
		cout<<v[i]<<"="<<v2[i]<<"\n";\
	}\
	cout<<v[v.size()-1]<<"="<<v2[v2.size()-1]<<"\n\n";\
}
using namespace std ;
const int kMaxN = 5e5 + 5 , MOD = 998244353 , INF = 1e9 ;
struct Edgepr
{
	int u , w ;
};
struct Edgeve
{
	int v , w ;
};
struct node
{
  int x , y , id ;
}Node[kMaxN] ;
inline ll ksm(ll a , ll b)
{
	ll mul = 1 ;
	while(b)
	{
		if(b & 1) mul *= a , mul %= MOD ;
		a *= a ;
		a %= MOD ;
		b >>= 1 ;
	}
	return mul ;
}
inline int read()
{
    int x = 0 , f = 1 ;
    char ch = getchar() ;
    while(ch < '0' || ch > '9')
    {
        if(ch == '-') f = -1 ;
        ch = getchar() ;
    }
    while(ch >= '0' && ch <= '9') x = x * 10 + ch - '0' , ch = getchar() ;
    return x * f ;
}
void write(int x)
{
    if(x < 0) putchar('-') , x = -x ;
    if(x > 9) write(x / 10) ;
    putchar(x % 10 + '0') ;
}
int n , m , q ;
vector<int> G[kMaxN] ;
int dep[kMaxN] , dp[kMaxN][25] ;
int sum , x = 1e9 ;
void dfs(int u , int fa)
{
	dep[u] = dep[fa] + 1 ;
	dp[u][0] = fa ;
	for( int i = 1 ; (1 << i) <= dep[u] ; i++ )
	{
		dp[u][i] = dp[dp[u][i - 1]][i - 1] ;
	}
	for( int i = 0 ; i < G[u].size() ; i++ )
	{
		int v = G[u][i] ;
		if(v == fa) continue ;
		dfs(v , u) ;
	}
}
int lca(int x , int y)
{
	if(dep[x] > dep[y]) swap(x , y) ;
	for( int i = 20 ; i >= 0 ; i-- )
	{
		if(dep[dp[y][i]] >= dep[x]) y = dp[y][i] ;
	}
	if(x == y) return y ;
	for( int i = 20 ; i >= 0 ; i-- )
	{
		if(dp[x][i] != dp[y][i]) y = dp[y][i] , x = dp[x][i] ;
	}
	return dp[x][0] ;
}
void init()
{
  
}
void work()
{
    init() ;
    cin >> n >> m >> q ;
    for( int i = 1 ; i < n ; i++ )
    {
    	int u , v ;
    	cin >> u >> v ;
    	G[u].push_back(v) ;
    	G[v].push_back(u) ;
	}
	dfs(q , 0) ;
	while(m--)
	{
		int x , y ;
		cin >> x >> y ;
		cout << lca(x , y) << "\n" ;
	}
}
signed main()
{
//	freopen(".in" , "r" , stdin) ;
//	freopen(".out" , "w" , stdout) ;
	ios::sync_with_stdio(0) , cin.tie(0) , cout.tie(0) ;
	int t = 1 ;
	// cin >> t ;
	while(t--) work() ;
	return 0 ;
}

LibreOJ 10134

容斥原理,加上了边权。

C++
//Code by hhy
#include<bits/stdc++.h>
#define F(i , a , b , c) for( int i = (a) ; ((c > 0) ? i <= (b) : i >= (b)) ; i += c )
#define T(i , root , b , c) for( int i = root ; b ; c )
#define int long long
#define W(f) while(f)
#define ull unsigned long long
#define pb push_back
#define fi first
#define se second
#define ll long long
#define debug(...){\
	cout<<"debug in function "<<__FUNCTION__<<",line "<<__LINE__<<"\n";\
	string s=#__VA_ARGS__,s2="";\
	vector<string>v;\
	for(auto i:s){\
		if(i==','){\
			v.push_back(s2);\
			s2="";\
		}else{\
			s2+=i;\
		}\
	}\
	v.push_back(s2);\
	vector<int>v2={__VA_ARGS__};\
	for(int i=0;i<v.size()-1;i++){\
		cout<<v[i]<<"="<<v2[i]<<"\n";\
	}\
	cout<<v[v.size()-1]<<"="<<v2[v2.size()-1]<<"\n\n";\
}
using namespace std ;
const int kMaxN = 2e4 + 5 , MOD = 998244353 , INF = 1e9 ;
struct Edgepr
{
	int u , w ;
};
struct Edgeve
{
	int v , w ;
};
struct node
{
  int x , y , id ;
}Node[kMaxN] ;
inline ll ksm(ll a , ll b)
{
	ll mul = 1 ;
	while(b)
	{
		if(b & 1) mul *= a , mul %= MOD ;
		a *= a ;
		a %= MOD ;
		b >>= 1 ;
	}
	return mul ;
}
inline int read()
{
    int x = 0 , f = 1 ;
    char ch = getchar() ;
    while(ch < '0' || ch > '9')
    {
        if(ch == '-') f = -1 ;
        ch = getchar() ;
    }
    while(ch >= '0' && ch <= '9') x = x * 10 + ch - '0' , ch = getchar() ;
    return x * f ;
}
void write(int x)
{
    if(x < 0) putchar('-') , x = -x ;
    if(x > 9) write(x / 10) ;
    putchar(x % 10 + '0') ;
}
int n , q ;
vector<Edgeve> G[kMaxN] ;
int dep[kMaxN] , dis[kMaxN] , dp[kMaxN][25] ;
void dfs(int u , int fa , int w)
{
	dis[u] = dis[fa] + w ;
	dep[u] = dep[fa] + 1 ;
	dp[u][0] = fa ;
	for( int i = 1 ; (1 << i) <= dep[u] ; i++ )
	{
		dp[u][i] = dp[dp[u][i - 1]][i - 1] ;
	}
	for( int i = 0 ; i < G[u].size() ; i++ )
	{
		int v = G[u][i].v ;
		if(v == fa) continue ;
		dfs(v , u, G[u][i].w) ;
	}
}
int lca(int x , int y)
{
	if(dep[x] > dep[y]) swap(x , y) ;
	for( int i = 20 ; i >= 0 ; i-- )
	{
		if(dep[dp[y][i]] >= dep[x]) y = dp[y][i] ;
	}
	if(x == y) return y ;
	for( int i = 20 ; i >= 0 ; i-- )
	{
		if(dp[x][i] != dp[y][i]) y = dp[y][i] , x = dp[x][i] ;
	}
	return dp[x][0] ;
}
void init()
{
  
}
void work()
{
    init() ;
    cin >> n >> q ;
    for( int i = 1 ; i < n ; i++ )
    {
    	int u , v , w ;
    	cin >> u >> v >> w ;
    	G[u].push_back({v , w}) ;
    	G[v].push_back({u , w}) ;
	}
	dfs(n , 0 , 1) ;
	while(q--)
	{
		int x , y ;
		cin >> x >> y ;
		cout << dis[x] + dis[y] - dis[lca(x , y)] * 2 << "\n" ;
	}
}
signed main()
{
//	freopen(".in" , "r" , stdin) ;
//	freopen(".out" , "w" , stdout) ;
	ios::sync_with_stdio(0) , cin.tie(0) , cout.tie(0) ;
	int t = 1 ;
	// cin >> t ;
	while(t--) work() ;
	return 0 ;
}
原文