zoukankan      html  css  js  c++  java
  • Kruskal板子

    #include<stdio.h>
    #include<algorithm>
    #include<iostream>
    using namespace std;
    #define maxn 100
    int V,E,res,father[maxn];
    struct edge
    {
        int u,v,cost;
    }es[maxn];
    bool cmp(struct edge a,struct edge b)
    {
        return a.cost<b.cost;
    }
    void init()
    {
        for(int i=1;i<=V;i++)
            father[i]=i;
    }
    int myfind(int x)
    {
        int t=x,tt;
        while(father[t]!=t) t=father[t];
        while(t!=x)
        {
            tt=father[x];
            father[x]=t;
            x=tt;
    
        }
        return t;
    
    }
    int same(int u,int v)
    {
        if(myfind(u)==myfind(v))
            return 1;
        return 0;
    }
    void unite(int x,int y)
    {
        x=myfind(x);
        y=myfind(y);
        father[x]=y;
    }
    void kruskal()
    {
        init();
        sort(es,es+E,cmp);
        for(int i=0;i<E;i++)
        {
            if(!same(es[i].u,es[i].v))
            {
                unite(es[i].u,es[i].v);
                res+=es[i].cost;
            }
        }
    
    
    }
    int main()
    {
        cin>>V>>E;
        for(int i=0;i<E;i++)
        {
            cin>>es[i].u>>es[i].v>>es[i].cost;
        }
        kruskal();
        cout<<res<<endl;
    
    }
    //
    5 2
    1 2
    1 3
    1 4
    1 5
    2 3
    2 4
    2 5
    3 4
    3 5
    4 5
    //
    #include<bits/stdc++.h>//终极版
    using namespace std;
    struct edge
    {
        int u,v;
        int cost;
    }e[500000+10];
    int father[100000+10];
    bool cmp(const edge&a,const edge&b)
    {
        return a.cost<b.cost;
    }
    int ifind(int x)
    {
        if(x!=father[x])
           return  father[x]=ifind(father[x]);
        else
            return x;
    }
    int main()
    {
        int n,m;
        int ans=0;
        scanf("%d %d",&n,&m);
        for(int i=1;i<=m;i++)
        {
            int u,v;
            int cost;
            scanf("%d %d %d",&u,&v,&cost);
            e[i].u=u;
            e[i].v=v;
            e[i].cost=cost;
        }
        for(int i=1;i<=n;i++)
            father[i]=i;
        sort(e+1,e+m+1,cmp);
        for(int i=1;i<=m;i++)
        {
            int u=e[i].u,v=e[i].v;
            int cost=e[i].cost;
            int uz=ifind(u),vz=ifind(v);
            if(uz==vz) continue;
            father[uz]=vz;
            ans+=cost;
        }
        cout<<ans<<endl;
        return 0;
    
    
    }
    
  • 相关阅读:
    Supervisor
    JS操作JSON总结
    电脑连接海信电视 HDMI
    upupw nginx服务器 rewrite设置
    PHP实现远程图片下载
    web页面调用IOS的事件
    composer更新不成功,启用国内镜像网站的配置更改办法
    Oracle中的一连接语句
    Oracle 树操作(select…start with…connect by…prior)
    MyEclipse下Tomcat无法部署项目 finish按钮无法点击
  • 原文地址:https://www.cnblogs.com/eason9906/p/11754937.html
Copyright © 2011-2022 走看看