HDU 3371 Connect the Cities

并查集+set容器 Kruskal

#include <stdio.h>
#include
<string.h>
#include
<set>
using namespace std;
const int MAXN = 501;
struct E
{
int x,y;
int weight;
};
E edge[
25001];
int father[MAXN];

int cmp(const void *d1,const void *d2){
return (*(E*)d1).weight - (*(E*)d2).weight;
}

void makeSet(int n){
for(int i = 0; i <= n; i++)
father[i]
= i;
}

int find(int x){
if(x != father[x])
father[x]
= find(father[x]);
return father[x];
}

void merge(int x, int y){
if(x > y){
father[x]
= y;
}
else {
father[y]
= x;
}
}

int main(){
set<int> s;
int cas,n,m,k,cost;
scanf(
"%d",&cas);
while( cas-- ){
scanf(
"%d %d %d",&n, &m, &k);
s.clear();
makeSet(n);
cost
= 0;
for(int i = 1; i <= m; i++){
scanf(
"%d%d%d",&edge[i].x,&edge[i].y,&edge[i].weight);
}
int num,first,city;
for(int i = 1; i <= k;i++){
scanf(
"%d%d",&num,&first);
for(int j = 1; j < num; j++){
scanf(
"%d",&city);
int xx = find(first);
int yy = find(city);
if(xx != yy)
merge(xx,yy);
}
}
qsort(edge
+1,m,sizeof(E),cmp);
for(int i = 1; i <= m; i++){
int xx = find(edge[i].x);
int yy = find(edge[i].y);
if(xx != yy){
merge(xx,yy);
cost
+= edge[i].weight;
}
}
for(int i = 1; i <= n; i++){
find(i);
}
for(int i = 1; i <= n; i++){
s.insert(father[i]);
}
if(s.size() > 1){
printf(
"-1\n");
}
else {
printf(
"%d\n",cost);
}
}
return 0;
}

posted @ 2011-04-21 14:20  L..  阅读(277)  评论(0编辑  收藏  举报