zoukankan      html  css  js  c++  java
  • [luogu4234]最小差值生成树

    [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 link(int x,int y){makert(x);fa[x]=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);
    		link(x,i+n);link(y,i+n);
    		if(cnt==n-1)ans=min(ans,w-*s.begin());
    	}
    	printf("%d
    ",ans);
    	return 0;
    }
    
  • 相关阅读:
    函数调用与参数传递总结(完成)
    序列总结
    python中如何调用.py文件
    反射获取Class对象的方式有哪些,反射创建对象的方式有哪些
    Dubbo的协议
    长连接和短连接
    hashset 和 treeset
    说说你对java中GC机制的理解
    找不着 jdbc 配置文件解决方案
    web.xml标准配置
  • 原文地址:https://www.cnblogs.com/sdzwyq/p/10114549.html
Copyright © 2011-2022 走看看