zoukankan      html  css  js  c++  java
  • HDU1879 继续畅通工程(最小生成树)

    省政府“畅通工程”的目标是使全省任何两个村庄间都可以实现公路交通(但不一定有直接的公路相连,只要能间接通过公路可达即可)。现得到城镇道路统计表,表中列出了任意两城镇间修建道路的费用,以及该道路是否已经修通的状态。现请你编写程序,计算出全省畅通需要的最低成本。 

    Input测试输入包含若干测试用例。每个测试用例的第1行给出村庄数目N ( 1< N < 100 );随后的 N(N-1)/2 行对应村庄间道路的成本及修建状态,每行给4个正整数,分别是两个村庄的编号(从1编号到N),此两村庄间道路的成本,以及修建状态:1表示已建,0表示未建。 

    当N为0时输入结束。Output每个测试用例的输出占一行,输出全省畅通需要的最低成本。Sample Input

    3
    1 2 1 0
    1 3 2 0
    2 3 4 0
    3
    1 2 1 0
    1 3 2 0
    2 3 4 1
    3
    1 2 1 0
    1 3 2 1
    2 3 4 1
    0

    Sample Output

    3
    1
    0
    #include<iostream>
    #include<algorithm>
    #include<cstdio>
    #include<cmath>
    using namespace std;
    const int maxn=105,INF=1e9;
    struct edge
    {
        int u,v,cost;
    }es[maxn*maxn];
    bool cmp(const edge& x,const edge& y)
    {
        return x.cost<y.cost;
    }
    int par[maxn],n;
    void init()
    {
        for(int i=1;i<=n;i++)
            par[i]=i;
    }
    int find(int x)
    {
        return x==par[x]?x:par[x]=find(par[x]);
    }
    void unite(int x,int y)
    {
        x=find(x);
        y=find(y);
        if(x!=y)
            par[x]=y;
    }
    bool same(int x,int y)
    {
        return find(x)==find(y);
    }
    int kruskal()
    {
        sort(es,es+n*(n-1)/2,cmp);
        init();
        int res=0;
        for(int i=0;i<n*(n-1)/2;i++)
        {
            edge e=es[i];
            if(!same(e.u,e.v))
            {
                unite(e.u,e.v);
                res+=e.cost;
            }
        }
        return res;
    }
    int main()
    {
        while(cin>>n,n)
        {
            int x,y,cos,t;
            for(int i=0;i<n*(n-1)/2;i++)
            {
                scanf("%d%d%d%d",&x,&y,&cos,&t);
                es[i].u=x;
                es[i].v=y;
                if(t)
                    es[i].cost=0;
                else
                    es[i].cost=cos;
            }
            cout<<kruskal()<<endl;
        }
        return 0;
    }
  • 相关阅读:
    PAT顶级 1024 Currency Exchange Centers (35分)(最小生成树)
    Codeforces 1282B2 K for the Price of One (Hard Version)
    1023 Have Fun with Numbers (20)
    1005 Spell It Right (20)
    1092 To Buy or Not to Buy (20)
    1118 Birds in Forest (25)
    1130 Infix Expression (25)
    1085 Perfect Sequence (25)
    1109 Group Photo (25)
    1073 Scientific Notation (20)
  • 原文地址:https://www.cnblogs.com/orion7/p/7372442.html
Copyright © 2011-2022 走看看