zoukankan      html  css  js  c++  java
  • HDU 3371 Connect the Cities

    链接:http://acm.hdu.edu.cn/showproblem.php?pid=3371


    跟畅通工程基本上一模一样。注意有重边的情况


    #include <iostream>
    #include<queue>
    #include<cstdio>
    #define MAX_N 505
    using namespace std;
    
    int par[MAX_N];
    int rankh[MAX_N];
    class rode
    {
    public:
    
        int from;
        int to;
        int cost;
    };
    class cmp
    {
    public:
    
        bool operator () (const rode &na,const rode &nb)
        {
            return na.cost>nb.cost;
        }
    };
    priority_queue <rode,vector<rode>,cmp> que;
    void init(int n)        //初始化
    {
        for(int i=1;i<=n;i++)
        {
            par[i]=i;
            rankh[i]=0;
        }
    
    }
    int findt(int x)        //查询
    {
        if(par[x]==x)
            return x;
        else
            return par[x]=findt(par[x]);
    }
    
    void unite(int x,int y)        //合并
    {
        x=findt(x);
        y=findt(y);
        if(x==y)
            return;
        if(rankh[x]<rankh[y])
            par[x]=y;
        else
        {
            par[y]=x;
            if(rankh[x]==rankh[y])
                rankh[x]++;
        }
    }
    bool same(int x,int y)
    {
        return findt(x)==findt(y);
    }
    int main()
    {
        int T;
        int t;
        int n,m,k;
        int a,b;
        int ans;
        rode r;
        scanf("%d",&T);
        while(T--)
        {
            while(!que.empty())
                que.pop();
            ans=0;
            scanf("%d%d%d",&n,&m,&k);
            init(n);
            while(m--)
            {
                scanf("%d%d%d",&r.from,&r.to,&r.cost);
                que.push(r);
            }
            while(k--)
            {
                scanf("%d%d",&t,&a);
                t--;
                while(t--)
                {
                    scanf("%d",&b);
                    if(!same(a,b))
                    {
                        unite(a,b);
                        n--;
                    }
                }
            }
            while(n!=1)
            {
                if(que.empty())
                {
                    ans=-1;
                    break;
                }
                else
                {
                    r = que.top();
                    que.pop();
                    if(!same(r.from,r.to))
                    {
                        unite(r.from,r.to);
                        n--;
                        ans+=r.cost;
                    }
                }
    
            }
            printf("%d
    ",ans);
        }
        return 0;
    }


  • 相关阅读:
    WCF ria services完美登陆功能(10)
    利用DYCOM快速建立wcf服务器端
    DYCom简要介绍
    断剑
    生命的价值
    飞翔的蜘蛛
    JSP中如何获取select标签选中的值
    wrapClass
    iconfont 在vue项目中的应用(iconcomponent组件)
    正则表达式
  • 原文地址:https://www.cnblogs.com/frankM/p/4399489.html
Copyright © 2011-2022 走看看