HDU3371 Connect the Cities

思考:用G++  TLE, 用C++ AC。

#include <iostream>
#include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;
const int maxn = 510;
int gn, gm;
//Accepted	3371	906MS	1088K	1336 B	C++	
//Accepted	3371	875MS	1088K	1471 B	C++	
struct edges{
	int x, y, w;
};
int f[maxn+10];

vector<edges> v;

int getFather(int x) {
    int t = x, j;
	while(t != f[t]) t = f[t];
	int k = x;
	while(k != t) {
        j = f[k];
        f[k] = t;
        k = f[k];
	}
	return t;
}
bool cmp(edges a, edges b) {
	if(a.w < b.w) return true;
	else return false;
}

int main()
{
	int T;
	int k;
	scanf("%d", &T);
	while(T--) {
		scanf("%d%d%d", &gn, &gm, &k);
		edges t;
		v.clear();
		for(int i = 0; i < gm; i++) {
			scanf("%d%d%d", &t.x, &t.y, &t.w);
			v.push_back(t);
		}
		int z, first;
		int cnt = gn;
		int bound;
		for(int i = 1; i <= maxn; i++) f[i] = i;
		for(int i = 0; i < k; i++) {
			scanf("%d", &bound);
			scanf("%d", &first);
			for(int j = 1; j < bound; j++) {
				scanf("%d", &z);
				int t1 = getFather(first);
				int t2 = getFather(z);
				if(t1 != t2) {
					f[t2] = t1;
					cnt--;
				}
			}
		}
		int ans = 0;
		sort(v.begin(), v.end(), cmp);
		for(int i  = 0; i < (int)v.size(); i++) {
			int t1 = getFather(v[i].x);
			int t2 = getFather(v[i].y);
			if(t1 != t2) {
				f[t2] = t1;
				cnt--;
				ans += v[i].w;
				if(cnt == 1) break;
			}
		}
		if(cnt == 1) {
			printf("%d\n", ans);
		} else {
			printf("-1\n");
		}
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值