LCT 动态维护 LCA

步骤如下:

1. 将当前查询需要的根makeroot, 表示为当前根下的lca

2. 将x Access到根, 此时x到根的路径是一棵平衡树

3. 将y Access, 中途遇到了与根一棵平衡树的点就记录下来(即与x到根的路径相遇), 返回即可


 模板传送门

#include<bits/stdc++.h>
#define N 500050
#define ls t[x].ch[0]
#define rs t[x].ch[1]
using namespace std;
int n,m,rt;
struct LCT{int ch[2],fa,tag;}t[N];
int read(){
    int cnt=0,f=1;char ch=0;
    while(!isdigit(ch)){if(ch=='-')f=-1;ch=getchar();}
    while(isdigit(ch))cnt=cnt*10+(ch-'0'),ch=getchar();
    return cnt*f;
}
bool isRoot(int x){
	int fa = t[x].fa; if(!fa) return true;
	return t[fa].ch[0] != x && t[fa].ch[1] != x;
}
void Pushdown(int x){
	if(t[x].tag){
		swap(ls,rs); 
		t[ls].tag ^= 1; t[rs].tag ^= 1;
		t[x].tag = 0;
	}
}
void Pushpath(int x){
	if(!isRoot(x)) Pushpath(t[x].fa);
	Pushdown(x);
}
void rotate(int x){
	int y = t[x].fa, z = t[y].fa;
	int k = (t[y].ch[1]==x);
	if(!isRoot(y)) t[z].ch[t[z].ch[1]==y] = x;
	t[x].fa = z;
	t[y].ch[k] = t[x].ch[k^1];
	t[t[x].ch[k^1]].fa = y;
	t[x].ch[k^1] = y; t[y].fa = x;
}
void Splay(int x){
	Pushpath(x);
	while(!isRoot(x)){
		int y = t[x].fa, z = t[y].fa;
		if(!isRoot(y))
			(t[y].ch[0]==x) ^ (t[z].ch[0]==y) ? rotate(x) : rotate(y);
		rotate(x);
	} 
}
int Access(int x){
	int tmp = 0;
	for(int y=0;x;y=x,x=t[x].fa)
		Splay(x), rs = y, tmp = x;
	return tmp;
}
void Makeroot(int x){ Access(x); Splay(x); t[x].tag ^= 1;}
void Link(int x,int y){ Makeroot(x); t[x].fa = y;}
int main(){
	n = read(), m = read(), rt = read();
	for(int i=1;i<n;i++){
		int x = read(), y = read();
		Link(x,y);
	} 
	Makeroot(rt);
	while(m--){
		int x = read(), y = read();
		Access(x); printf("%d\n",Access(y));
	} return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

FSYo

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值