# 【刷题】BZOJ 1977 [BeiJing2010组队]次小生成树 Tree

5 6
1 2 1
1 3 2
2 4 3
3 5 4
3 4 3
4 5 6

11

## Solution

#include<bits/stdc++.h>
#define ll long long
#define db double
#define ld long double
const int MAXN=100000+10,MAXM=300000+10;
int n,m,fa[MAXN];
ll lst,ext=1e18;
struct edge{
int u,v,w;
inline bool operator < (const edge &A) const {
return w<A.w;
};
};
edge side[MAXM];
template<typename T> inline void chkmin(T &x,T y){x=(y<x?y:x);}
template<typename T> inline void chkmax(T &x,T y){x=(y>x?y:x);}
template<typename T> inline T min(T x,T y){return x<y?x:y;}
template<typename T> inline T max(T x,T y){return x>y?x:y;}
#define lc(x) ch[(x)][0]
#define rc(x) ch[(x)][1]
struct LCT{
int ch[MAXN+MAXM][2],fa[MAXN+MAXM],Mx[MAXN+MAXM],SMx[MAXN+MAXM],rev[MAXN+MAXM],stack[MAXN+MAXM],val[MAXN+MAXM],cnt;
inline bool nroot(int x)
{
return lc(fa[x])==x||rc(fa[x])==x;
}
inline void reverse(int x)
{
std::swap(lc(x),rc(x));
rev[x]^=1;
}
inline void pushup(int x)
{
if(Mx[lc(x)]>Mx[rc(x)])Mx[x]=Mx[lc(x)],SMx[x]=max(Mx[rc(x)],SMx[lc(x)]);
else if(Mx[lc(x)]<Mx[rc(x)])Mx[x]=Mx[rc(x)],SMx[x]=max(Mx[lc(x)],SMx[rc(x)]);
else Mx[x]=Mx[lc(x)],SMx[x]=max(SMx[lc(x)],SMx[rc(x)]);
if(val[x]>Mx[x])SMx[x]=Mx[x],Mx[x]=val[x];
else if(val[x]!=Mx[x])chkmax(SMx[x],val[x]);
}
inline void pushdown(int x)
{
if(rev[x])
{
if(lc(x))reverse(lc(x));
if(rc(x))reverse(rc(x));
rev[x]=0;
}
}
inline void rotate(int x)
{
int f=fa[x],p=fa[f],c=(rc(f)==x);
if(nroot(f))ch[p][rc(p)==f]=x;
fa[ch[f][c]=ch[x][c^1]]=f;
fa[ch[x][c^1]=f]=x;
fa[x]=p;
pushup(f);
pushup(x);
}
inline void splay(int x)
{
cnt=0;
stack[++cnt]=x;
for(register int i=x;nroot(i);i=fa[i])stack[++cnt]=fa[i];
while(cnt)pushdown(stack[cnt--]);
for(register int y=fa[x];nroot(x);rotate(x),y=fa[x])
if(nroot(y))rotate((lc(y)==x)==(lc(fa[y])==y)?y:x);
pushup(x);
}
inline void access(int x)
{
for(register int y=0;x;x=fa[y=x])splay(x),rc(x)=y,pushup(x);
}
inline void makeroot(int x)
{
access(x);splay(x);reverse(x);
}
inline void split(int x,int y)
{
makeroot(x);access(y);splay(y);
}
{
makeroot(x);fa[x]=y;
}
};
LCT T;
#undef lc
#undef rc
template<typename T> inline void read(T &x)
{
T data=0,w=1;
char ch=0;
while(ch!='-'&&(ch<'0'||ch>'9'))ch=getchar();
if(ch=='-')w=-1,ch=getchar();
while(ch>='0'&&ch<='9')data=((T)data<<3)+((T)data<<1)+(ch^'0'),ch=getchar();
x=data*w;
}
template<typename T> inline void write(T x,char c='\0')
{
if(x<0)putchar('-'),x=-x;
if(x>9)write(x/10);
putchar(x%10+'0');
if(c!='\0')putchar(c);
}
inline int found(int x)
{
if(fa[x]!=x)fa[x]=found(fa[x]);
return fa[x];
}
int main()
{
for(register int i=1;i<=n;++i)fa[i]=i;
std::sort(side+1,side+m+1);
for(register int i=1,x,y,sn;i<=m;++i)
{
x=found(side[i].u),y=found(side[i].v);
sn=n+i;
if(x!=y)
{
fa[x]=y;
lst+=side[i].w;
T.val[sn]=T.Mx[sn]=side[i].w;