跳到正文

题解

题解 P3379 【【模板】最近公共祖先(LCA)】

Soulist约 5 分钟
原文
文章信息与版本

文章信息

发布
2019年3月20日
收录
2025年12月12日
更新
2026年9月11日
篇幅
约 5 分钟
获赞
34
题目
P3379

版本

  1. v1当前

很多时候我们会遇到要求 LCALCA 的题目,然而实际上求 LCALCA 也是可以毒瘤一些的 (主要是我弱 QAQ ) 。当我们需要求以某个点s(ss(s会变))为根的 LCALCA 时就需要 LCTLCT

首先LCTLCT是可以加边的,所以我们需要一个linklink操作

但是因为给定了一棵树,所以我们并不需要findrootfindroot来判断加边是否合法

然后考虑ss为根,所以我们需要makeroot(s)makeroot(s)

然后每次询问LCA(x,y)LCA(x,y),我们可以发现,如果先access(x)access(x),那么xx和根在了一个SplaySplay

然后不难发现,LCALCA显然也在这颗SplaySplay中,那么我们再考虑access(y)access(y)

不难发现,因为LCALCA和xx在一颗SplaySplay中,所以yy到LCALCA一定是一条虚边,故在access(y)access(y)的时候每次记录跳过的虚边是跳到了谁那里,然后将最后一次跑虚边的点(父亲),作为LCALCA输出。

详见代码:

C++
#include<bits/stdc++.h>
using namespace std;
#define il inline
#define ls(x) t[x].son[0]
#define rs(x) t[x].son[1]
il int read() {
	char cc = getchar(); int cn = 0, flus = 1;
	while(cc < '0' || cc > '9') {  if( cc == '-' ) flus = -flus;  cc = getchar();  }
	while(cc >= '0' && cc <= '9')  cn = cn * 10 + cc - '0', cc = getchar();
	return cn * flus;
}
const int N = 5e5 + 5;
struct LCT {
	int son[2], fa;
	bool mark;
}t[N];
int n, m, s;
bool isroot( int x ) {
	return ( ls(t[x].fa) != x ) && ( rs(t[x].fa) != x );
}
void pushmark( int x ) {
	if( t[x].mark ) {
		t[x].mark = 0, t[ls(x)].mark ^= 1, t[rs(x)].mark ^= 1;
		swap( ls(x), rs(x) );
	}
}
il void rotate( int x ) {
	int f = t[x].fa, ff = t[f].fa, qwq = ( rs(f) == x );
	t[x].fa = ff;
	if( !isroot(f) ) t[ff].son[rs(ff) == f] = x;
	t[t[x].son[qwq ^ 1]].fa = f, t[f].son[qwq] = t[x].son[qwq ^ 1];
	t[x].son[qwq ^ 1] = f, t[f].fa = x;
}
int st[N];
il void Splay( int x ) {
	int top = 0, now = x; st[++top] = now;
	while( !isroot(now) ) st[++top] = ( now = t[now].fa );
	while( top ) pushmark( st[top--] );
	while( !isroot(x) ) {
		int f = t[x].fa, ff = t[f].fa;
		if( !isroot(f) ) ( ( rs(ff) == f ) ^ ( rs(f) == x ) ) ? rotate(f) : rotate(x);
		rotate( x );
	}
}
void access( int x ) {
	for( int y = 0; x; y = x, x = t[y].fa ) {
		Splay( x ), t[x].son[1] = y;
	}
}
void makeroot( int x ) {
	access( x ), Splay( x ), t[x].mark ^= 1, pushmark( x );
}
void link( int x, int y ) {
	makeroot( x ), t[x].fa = y;
}
int LCA( int x, int y ) {
	access( x );
	int ans = y;
	for( int i = 0; y; ans = i = y, y = t[i].fa ) {
		Splay( y ), t[y].son[1] = i;
	}
	return ans;
}
signed main()
{
	n = read(), m = read(), s = read();
	int x, y;
	for( register int i = 1; i < n; ++ i )
		x = read(), y = read(), link( x, y );
	makeroot(s);
	for( register int i = 1; i <= m; ++ i ) {
		x = read(), y = read();
		printf("%d\n", LCA( x, y ));
	}
	return 0;
}
原文
存档评论8 条抓取于