【最小生成树 并查集】hdu 3371 Connect the Cities

来源:互联网 发布:阿基拉和拼字比赛 知乎 编辑:程序博客网 时间:2024/06/05 00:40

题意:给你n个点,m条边,k个已经互相联通的团。求最小生成树的代价。


#include <stdio.h>#include <map>#include <math.h>#include <algorithm>#include <string>#include <string.h>#include <iostream>#define mm(a) memset(a, 0, sizeof(a))#define Max 555using namespace std;int father[Max], vis[Max];int n, m;struct ro{    int from, to, w;} road[25002*3];bool cmp(ro a, ro b){    return a.w < b.w;}int findd(int r){    if(r != father[r]) father[r] = findd(father[r]);    return father[r];}int main(){    int t;    scanf("%d", &t);    while(t--)    {        int k;        scanf("%d%d%d", &n, &m, &k);        for(int i = 0; i < m; i ++)            scanf("%d%d%d", &road[i].from, &road[i].to, &road[i].w);        for(int i = 0; i <= n; i ++)            father[i] = i;        while(k--)        {            int q;            scanf("%d", &q);            int pre = 0;            while(q--)            {                int cur;                scanf("%d", &cur);                if(pre)                {                    int a = findd(pre);                    int b = findd(cur);                    father[a] = b;                }                pre = cur;            }        }        sort(road, road + m, cmp);        int cost = 0;        for(int i = 0; i < m; i ++)        {            int aa = findd(road[i].from);            int bb = findd(road[i].to);            if(aa != bb)            {                cost += road[i].w;                father[aa] = bb;            }        }        int cnt = 0;        for(int i = 1; i <= n; i ++)        {            if(i == father[i])                cnt ++;        }        if(cnt > 1) puts("-1");        else if(cnt == 1) printf("%d\n", cost);    }    return 0;}


0 0
原创粉丝点击