# [luogu4234]最小差值生成树

luogu

lct维护
$$ans=min(E_{max}-E_{min})$$

#include<bits/stdc++.h>
using namespace std;
const int _=4e5+5;
int re(){
int x=0,w=1;char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')w=-1;ch=getchar();}
while(ch>='0'&&ch<='9')x=x*10+ch-'0',ch=getchar();
return x*w;
}
int n,m,top,ans=1e9,cnt;
int f[_],fa[_],id[_],st[_],val[_],rev[_],ch[2][_];
multiset<int>s;
struct edge{int u,v,w;}e[_];
bool cmp(edge a,edge b){return a.w<b.w;}
int find(int x){return x==f[x]?x:f[x]=find(f[x]);}
int son(int x){return x==ch[1][fa[x]];}
bool isrt(int x){return x^ch[1][fa[x]]&&x^ch[0][fa[x]];}
void rever(int x){if(x)swap(ch[0][x],ch[1][x]),rev[x]^=1;}
void pd(int x){if(rev[x])rever(ch[0][x]),rever(ch[1][x]),rev[x]=0;}
void pu(int x){
id[x]=x;
if(ch[0][x]&&val[id[ch[0][x]]]<val[x])id[x]=id[ch[0][x]];
if(ch[1][x]&&val[id[ch[1][x]]]<val[id[x]])id[x]=id[ch[1][x]];
}
void rotate(int x){
int y=fa[x],z=fa[y],k=son(x);
ch[k][y]=ch[k^1][x];if(ch[k][y])fa[ch[k][y]]=y;
fa[x]=z;if(!isrt(y))ch[son(y)][z]=x;
fa[y]=x;ch[k^1][x]=y;pu(y);
}
void splay(int x){
st[top=1]=x;
for(int i=x;!isrt(i);i=fa[i])st[++top]=fa[i];
while(top)pd(st[top--]);
for(int y=fa[x];!isrt(x);rotate(x),y=fa[x])
if(!isrt(y))rotate(son(x)^son(y)?x:y);
pu(x);
}
void access(int x){for(int y=0;x;y=x,x=fa[x])splay(x),ch[1][x]=y,pu(x);}
void makert(int x){access(x);splay(x);rever(x);}
void split(int x,int y){makert(x);access(y);splay(y);}
void cut(int x,int y){split(x,y);fa[x]=ch[0][y]=0;}
int main(){
n=re(),m=re();
memset(val,63,sizeof(val));
for(int i=1;i<=n;i++)f[i]=i;
for(int i=1;i<=m;i++)
e[i].u=re(),e[i].v=re(),e[i].w=re();
sort(e+1,e+m+1,cmp);
for(int i=1;i<=m;i++){
int x=e[i].u,y=e[i].v,w=e[i].w;
if(x==y)continue;
if(find(x)==find(y)){
split(x,y);
int k=id[y];
cut(e[k-n].u,k);
cut(e[k-n].v,k);
s.erase(s.lower_bound(e[k-n].w));
}
else ++cnt,f[f[x]]=f[y];
val[i+n]=w;s.insert(w);