zcmimi's blog
avatar
zc
2020-04-01 23:48:00
  • 本文总阅读量
查看原题

点击跳转

按边权从小到大排序后,依次添加边

问题转化为了:

每次加边的时候,

如果两点为连通,则加边

否则在目前的生成树上找到边权最小的边, 并替换为新边

可以用LCT维护

#include<bits/stdc++.h>
#pragma GCC optimize(3)
#define il __inline__ __attribute__ ((always_inline))
il int min(int x,int y){return x<y?x:y;}
namespace IN{const int str=1<<20;static char in_buf[str],*in_s,*in_t;bool __=0;inline char gc(){return (in_s==in_t)&&(in_t=(in_s=in_buf)+fread(in_buf,1,str,stdin)),in_s==in_t?EOF:*in_s++;}template<typename T>inline void in(T &x){if(__)return;char c=gc();bool f=0;while(c!=EOF&&(c<'0'||c>'9'))f^=(c=='-'),c=gc();if(c==EOF){__=1;return;}x=0;while(c!=EOF&&'0'<=c&&c<='9')x=x*10+c-48,c=gc();if(c==EOF)__=1;if(f)x=-x;}template<typename T,typename ... arr>inline void in(T &x,arr & ... y){in(x),in(y...);}}using namespace IN;
const int N=250001,inf=-1u>>1;
int n,m,rev[N],c[2][N],f[N],s[N];
struct edge{int x,y,w;bool operator<(edge t){return w<t.w;}}e[N];
#define ls(x) c[0][x]
#define rs(x) c[1][x]
il void pu(int x){s[x]=min(x>n?x:inf,min(s[ls(x)],s[rs(x)]));}
il void pr(int x){rev[x]^=1;int t=ls(x);ls(x)=rs(x),rs(x)=t;}
il void pd(int x){
    if(rev[x]){
        if(ls(x))pr(ls(x));
        if(rs(x))pr(rs(x));
        rev[x]=0;
    }
}
il int g(int x){return rs(f[x])==x;}
il int nrt(int x){return ls(f[x])==x||rs(f[x])==x;}
il void rotate(int x){
    int y=f[x],z=f[y],l=g(x),r=!l,w=c[r][x];
    if(nrt(y))c[g(y)][z]=x;
    c[r][x]=y,c[l][y]=w;
    if(w)f[w]=y;
    f[x]=z,f[y]=x;
    pu(y),pu(x);
}
int st[N];
il void splay(int x){
    int z=0,y=st[++z]=x;
    while(nrt(y))st[++z]=y=f[y];
    while(z)pd(st[z--]);
    for(;nrt(x);rotate(x))if(nrt(f[x]))
        rotate(g(x)^g(f[x])?x:f[x]);
}
il void access(int x){for(int y=0;x;x=f[y=x])splay(x),rs(x)=y,pu(x);}
il void mrt(int x){access(x),splay(x),pr(x);}
il int frt(int x){
    for(access(x),splay(x);ls(x);pd(x),x=ls(x));
    splay(x);return x;
}
il void link(int x,int y){mrt(x),f[x]=y;}
bool b[N];
int main(){
    s[0]=inf;
    in(n,m);
    for(int i=1;i<=m;++i)in(e[i].x,e[i].y,e[i].w);
    std::sort(e+1,e+m+1);
    int x,y,t=n,tt=0,p=1,ans=inf;
    for(int i=1;i<=m;++i){
        x=e[i].x,y=e[i].y;++t;
        if(x==y){b[i]=1;continue;}
        mrt(x);
        if(frt(y)!=x)f[f[x]=t]=y,++tt;
        else{
            mrt(x),access(y),splay(y);
            int now=s[y];
            b[now-n]=1;splay(now);
            f[ls(now)]=f[rs(now)]=0;
            link(x,t),link(t,y);
        }
        while(b[p]&&p<=i)++p;
        if(tt>=n-1)ans=min(ans,e[i].w-e[p].w);
    }
    printf("%d\n",ans);
}
LG 4234 最小差值生成树
comment评论
Search
search