2017.12.24
有时候AC,有时候TL
#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
using namespace std;
int pre[505];
void init(int n){
for(int i = 1; i <= n; i++)
pre[i] = i;
}
int find(int x){
int root = x;
while(root != pre[root])
root = pre[root];
while(x != root){
int t = pre[x];
pre[x] = root;
x = t;
}
return root;
// if(pre[x] != x)
// pre[x] = find(pre[x]);
// return pre[x];
}
struct node{
int u;
int v;
int path;
};
node Edge[100000];
bool cmp(node a, node b){
return a.path < b.path;
}
int main(){
int T;
cin >> T;
while(T--){
int x, y, z;
int edge = 0, cost = 0;
scanf("%d%d%d", &x, &y, &z);
init(x);
for(int i = 0; i < y; i++){
scanf("%d%d%d", &Edge[i].u, &Edge[i].v, &Edge[i].path);
}
sort(Edge, Edge+y, cmp);
for(int i = 0; i < z; i++){
int cnt, root;
scanf("%d%d", &cnt, &root);
for(int j = 1; j < cnt; j++){
int num;
scanf("%d", &num);
// join(no, no1);
int c1 = find(num), c2 = find(root);
if(c1 != c2)
pre[c1] = c2;
}
}
for(int i = 1; i <= x; i++)
if(pre[i] == i)
edge++;
bool flag = false;
for(int i = 0; i < y; i++){
// if(join(Edge[i].u, Edge[i].v)){
// cost += Edge[i].path;
// Number--;
// }
int tx = find(Edge[i].u), ty = find(Edge[i].v);
if(tx != ty){
pre[tx] = ty;
cost += Edge[i].path;
edge--;
}
if(edge == 1){
flag = true;
break;
}
}
// memset(con, 0, sizeof(con));
// for(i = 1; i <= x; i++){
// con[find(i)] = 1;
// }
//
// Number = 0;
//
// for(i = 1; i <= x; i++){
//
// if(con[i] == 1){
// Number++;
// }
// }
if(flag)
printf("%d\n",cost);
else
printf("-1\n");
}
return 0;
}