模板链接:https://www.luogu.org/problemnew/show/P3690
【模板】Link Cut Tree (动态树)
题目背景
动态树
题目描述
给定n个点以及每个点的权值,要你处理接下来的m个操作。操作有4种。操作从0到3编号。点从1到n编号。
0:后接两个整数(x,y),代表询问从x到y的路径上的点的权值的xor和。保证x到y是联通的。
1:后接两个整数(x,y),代表连接x到y,若x到y已经联通则无需连接。
2:后接两个整数(x,y),代表删除边(x,y),不保证边(x,y)存在。
3:后接两个整数(x,y),代表将点x上的权值变成y。
输入输出格式
输入格式:
第1行两个整数,分别为n和m,代表点数和操作数。
第2行到第n+1行,每行一个整数,整数在[1,10^9]内,代表每个点的权值。
第n+2行到第n+m+1行,每行三个整数,分别代表操作类型和操作所需的量。
输出格式
对于每一个0号操作,你须输出x到y的路径上点权的xor和。
输入输出样例
输入样例#1:
3 3
1
2
3
1 1 2
0 1 2
0 1 1
输出样例#1:
3
1
说明
数据范围: $ 1 \leq N, M \leq 3 \cdot {10}^5 $
题解
模板题博主都懒得写题解。。。按照惯例贴一波大佬的博客。
感觉 L C T \mathcal{LCT} LCT比 S p l a y \mathcal{Splay} Splay好写得多,1600就能写完。
博主的代码有些细节跟那位大佬不一样,各位可以自己体会一下。
代码
#include<bits/stdc++.h>
#define le son[v][0]
#define ri son[v][1]
using namespace std;
const int M=5e5+5;
int n,m,val[M],sum[M],son[M][2],dad[M],sta[M];
bool rev[M];
void in()
{
scanf("%d%d",&n,&m);
for(int i=1;i<=n;++i)
scanf("%d",&val[i]);
}
bool notroot(int v){return son[dad[v]][0]==v||son[dad[v]][1]==v;}
void up(int v){sum[v]=sum[le]^sum[ri]^val[v];}
void turn(int v){swap(le,ri);rev[v]^=1;}
void push(int v){if(!rev[v])return;if(le)turn(le);if(ri)turn(ri);rev[v]=0;}
void spin(int v)
{
int f,ff,k,w;
f=dad[v];ff=dad[f];k=son[f][1]==v;w=son[v][!k];
if(notroot(f))son[ff][son[ff][1]==f]=v;
son[v][!k]=f;son[f][k]=w;
if(w)dad[w]=f;
dad[f]=v;dad[v]=ff;
up(f);up(v);
}
void splay(int v)
{
int u=v,top=0,f,ff;
sta[++top]=u;
while(notroot(u))sta[++top]=u=dad[u];
while(top)push(sta[top--]);
while(notroot(v))
{
f=dad[v];ff=dad[f];
if(notroot(f))spin((son[f][0]==v)^(son[ff][0]==f)?v:f);
spin(v);
}
up(v);
}
void access(int v){for(int f=0;v;v=dad[f=v])splay(v),ri=f,up(v);}
void beroot(int v){access(v);splay(v);turn(v);}
int findroot(int v){access(v);splay(v);while(le)push(v),v=le;return v;}
void split(int x,int y){beroot(x);access(y);splay(y);}
void link(int x,int y){beroot(x);if(findroot(y)!=x)dad[x]=y;}
void cut(int v,int y){beroot(v);if(findroot(y)==v&&dad[v]==y&&!ri)dad[v]=son[y][0]=0,up(y);}
void ac()
{
int op,a,b;
for(int i=1;i<=m;++i)
{
scanf("%d%d%d",&op,&a,&b);
switch(op)
{
case 0:split(a,b);printf("%d\n",sum[b]);break;
case 1:link(a,b);break;
case 2:cut(a,b);break;
case 3:splay(a);val[a]=b;break;
}
}
}
int main()
{
in();ac();
return 0;
}

本文介绍了一道经典的动态树问题,并通过洛谷P3690题目详细讲解了LinkCutTree(LCT)的应用与实现。文章提供了完整的代码示例,展示了如何处理节点权值的异或和查询、节点连接与断开操作等。
1329

被折叠的 条评论
为什么被折叠?



