hdu_3371 Connect the Cities

#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <cstring>
using namespace std;
#define N 30000
int Father[N];
struct node
{
    int u,v,w;
} save[N];

bool cmp(node a,node b)
{
    return a.w<b.w;
}
void Make_set(int n)
{
    for(int i=0; i<=n; i++)
        Father[i] = i;
}

int Find(int x)
{
    int temp,ans,pre;
    pre = x;
    while(x != Father[x])
    {
        x = Father[x];
    }
    ans = x;
    while(pre != Father[pre])
    {
        temp = Father[pre];
        Father[pre] = ans;
        pre = temp;
    }
    return ans;
}

void Union(int a,int b)
{
    int x = Find(a);
    int y = Find(b);
    Father[x] = y;
}

int Is_connected(int n)
{
    int sum = 0;
    for(int i=1; i<=n; i ++)
        if(Father[i] == i)
            sum++;
    if(sum == 1)
        return 1;
    else
        return 0;
}
int main()
{
    int T,n,m,k,i,j,x,y,ans,res,sum,temp;
    int a[105];
    scanf("%d",&T);
    while(T--)
    {
        sum = 0;
        cin>>n>>m>>k;
        for(i=0; i<m; i++)
            scanf("%d%d%d",&save[i].u,&save[i].v,&save[i].w);
        sort(save,save+m,cmp);
        Make_set(n);
        for(i=0; i<k; i++)
        {
            scanf("%d",&temp);
            for(j=0; j<temp; j++)
            {
                scanf("%d",&a[j]);
                if(j)
                    Union(a[j],a[j-1]);
            }
        }
        for(i=0; i<m; i++)
        {
            x = Find(save[i].u);
            y = Find(save[i].v);
            if(x != y)
            {
                Union(save[i].u,save[i].v);
                sum += save[i].w;
            }
        }
        if(Is_connected(n))
            printf("%d\n",sum);
        else
            printf("-1\n");
    }
    return 0;
}

你可能感兴趣的:(Algorithm,HDU,Spanning,Tre,Minimun)