背景:
不要被标题迷惑了。
L
C
T
LCT
LCT啊。
题目传送门:
https://www.luogu.org/problemnew/show/P3366
题意:
求一个图的最小生成树。
思路:
别跟我讲
K
r
u
s
k
a
l
Kruskal
Kruskal和
P
r
i
m
Prim
Prim。
L
C
T
LCT
LCT维护最小生成树的模板(支持在线动态加边和删边)。
思路很简单。
每一次读入一条边
(
x
,
y
)
,
z
(
权
值
)
(x,y),z(权值)
(x,y),z(权值)。
按照
K
r
u
s
k
a
l
Kruskal
Kruskal的思想(类似,实现方式不同)。
如果不连通,就直接连上。
如果已经联通,就在
x
,
y
x,y
x,y的路径上找到最大的一条边,将其删除。
看图:
若15为当前边,那么20必须要删,因为这样也能保证
(
2
,
3
)
(2,3)
(2,3)联通,且能使得答案更加小。
因此正确性与
K
r
u
s
k
a
l
Kruskal
Kruskal一样,是对的。
因为此时
L
C
T
LCT
LCT维护的是边权,所以开虚拟节点。
假设
x
x
x连边到
y
y
y,那么取一点
p
p
p,让
x
x
x连边到
p
p
p,
y
y
y连边到
p
p
p(
p
p
p连边到
y
y
y,无向),将边权存在
p
p
p上即可。
操作时在判断是否在范围内即可。
代码:
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
struct node1{int d,fa,ma,pos,lazy,son[2];} tr[500010];
struct node2{int x,y,z;} a[500010];
int n,m,k=0,ans=0;
bool isroot(int x)
{
return tr[tr[x].fa].son[0]!=x&&tr[tr[x].fa].son[1]!=x;
}
bool isson(int x)
{
return x==tr[tr[x].fa].son[1];
}
void change(int x)
{
if(!x)return;
swap(tr[x].son[0],tr[x].son[1]);
tr[x].lazy^=1;
}
void pushup(int x)
{
int lc=tr[x].son[0],rc=tr[x].son[1];
tr[x].ma=tr[x].d,tr[x].pos=x;
if(tr[lc].ma>tr[x].ma) tr[x].ma=tr[lc].ma,tr[x].pos=tr[lc].pos;
if(tr[rc].ma>tr[x].ma) tr[x].ma=tr[rc].ma,tr[x].pos=tr[rc].pos;
}
void pushdown(int x)
{
if(!tr[x].lazy) return;
change(tr[x].son[0]),change(tr[x].son[1]);
tr[x].lazy=0;
}
void rot(int x)
{
int w=isson(x),y=tr[x].fa,yy=tr[y].fa;
tr[y].son[w]=tr[x].son[w^1];
if(tr[y].son[w]) tr[tr[y].son[w]].fa=y;
tr[x].fa=yy;
if(!isroot(y)) tr[yy].son[isson(y)]=x;
tr[x].son[w^1]=y;tr[y].fa=x;
pushup(y);
}
int sta[300010];
int top;
void splay(int x)
{
sta[top=1]=x;
for(int i=x;!isroot(i);i=tr[i].fa)
sta[++top]=tr[i].fa;
while(top) pushdown(sta[top--]);
for(int y=tr[x].fa;!isroot(x);rot(x),y=tr[x].fa)
if(!isroot(y)) isson(x)^isson(y)?rot(x):rot(y);
pushup(x);
}
void access(int x)
{
for(int y=0;x;y=x,x=tr[x].fa)
splay(x),tr[x].son[1]=y,pushup(x);
}
int findroot(int x)
{
access(x);splay(x);
while(tr[x].son[0]) x=tr[x].son[0];
//splay(x);
return x;
}
void makeroot(int x)
{
access(x);splay(x);change(x);
}
void link(int x,int y)
{
makeroot(x);
if(findroot(y)!=x) tr[x].fa=y;
}
void split(int x,int y)
{
makeroot(x);access(y);splay(y);
}
void del(int x,int y)
{
split(x,y);
tr[x].fa=tr[y].son[0]=0,pushup(x),pushup(y);
}
node1 query(int x,int y)
{
split(x,y);
return tr[y];
}
int main()
{
scanf("%d %d",&n,&m);
for(int i=0;i<=(n<<1);i++)
tr[i]=(node1){0,0,0,i,0,0,0};
for(int i=n+1;i<=n+m;i++)
{
scanf("%d %d %d",&a[i].x,&a[i].y,&a[i].z);
if(findroot(a[i].x)!=findroot(a[i].y))
{
tr[i].d=a[i].z;
link(a[i].x,i);link(a[i].y,i);
ans+=a[i].z;
k++;
}
else
{
node1 MAX=query(a[i].x,a[i].y);
if(MAX.pos>n&&a[i].z<MAX.ma)
{
del(a[MAX.pos].x,MAX.pos);del(a[MAX.pos].y,MAX.pos);
ans-=MAX.ma;
tr[i].d=a[i].z;
link(a[i].x,i);link(a[i].y,i);
ans+=a[i].z;
}
}
}
if(k==n-1) printf("%d",ans); else printf("orz");
}