首页 > 技术文章 > HDU 3371 Connect the Cities

frankM 2014-07-26 16:28 原文

链接: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\n",ans);
    }
    return 0;
}


推荐阅读