思考:用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;
}