zoukankan      html  css  js  c++  java
  • 最小生成树模板,构造,权值的求解

    待理解......

    #include<iostream>
    #include<cstdio>
    #include<cstring>
    #include<cmath>
    #include<queue>
    #include<set>
    #include<algorithm>
    #include<map>
    #define maxn 50010
    using namespace std;
    int par[maxn];
    int ranke[maxn];
    void init(int n)
    {
        for(int i=0;i<n;i++){
            par[i]=i;
            ranke[i]=0;
        }
    }
    int find(int x)//找父亲
    {
        if(par[x]==x)return x;
        else {
            return par[x]=find(par[x]);//递归找父亲(因为父亲是统一的)
        }
    }
    void unite(int x,int y)
    {
        x=find(x);
        y=find(y);
        if(x==y)return ;
        if(ranke[x]<ranke[y])
        {
            par[x]=y;
        }
        else par[y]=x;
        if(ranke[x]==ranke[y])ranke[x]++;
    }
    bool same(int x,int y)
    {
        return find(x)==find(y);
    }
    
    
    struct edge{
      int from,to,cost;
    }mp[maxn];;
    bool comp(const edge& e1,const edge& e2)
    {
        return e1.cost<e2.cost;
    }
     
    int V;//结点个数 
    int E;//关系个数 
    int res;
    int flag;
    int kruskal()
    {
        flag=1;
        sort(mp,mp+E,comp);
        init(V);
        res=0;
        for(int i=0;i<E;i++)
        {
            edge s=mp[i];
            if(!same(s.from,s.to)){
                unite(s.from,s.to);
                flag++;
            res+=s.cost;
            }
        }
        return res;
    }
    int main()
    {
        int d1,d2,dis;
       int mon;
       while(cin>>mon>>E>>V)
       {
           for(int i=0;i<E;i++)
           {
               cin>>d1>>d2>>dis;
               d1--;
               d2--;
                mp[i].from=d1;
                mp[i].to=d2;
                mp[i].cost=dis;
           }
            kruskal();
            //cout<<flag;
           cout<<res<<endl;;
        }
        return 0;
    }
  • 相关阅读:
    退役划水一
    Codeforces 1592F2 Alice and Recoloring 2
    AtCoder Regular Contest 108 选做
    AtCoder Regular Contest 107 选做
    AtCoder Regular Contest 106 选做
    AtCoder Regular Contest 105 选做
    2021 年铜陵市青少年编程大赛 部分题解
    Codeforces 1566G Four Vertices
    数据迁移的一般测试步骤
    mac常用命令
  • 原文地址:https://www.cnblogs.com/xiechenxi/p/8443309.html
Copyright © 2011-2022 走看看