练习图论中的最小生成树,全部用克鲁斯卡尔算法描述,因为比较简单。
这个题是事先有一些模块已经连好了,事先处理好p数组就可以了,然后注意一些边界细节问题,毕竟HDU没有调试数据,只有Accepted or Wrong Answer
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
class Main {
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static int N = 510, M = 25010, T, n, m, k, cnt;
static int p[];
static Pair road[];
public static void init() {
p = new int[N];
road = new Pair[M];
cnt = 0;
for (int i = 0; i < N; i++) p[i] = i;
}
public static void main(String[] args) throws IOException {
T = Integer.parseInt(br.readLine());
while (T-- > 0) {
init();
String s[] = br.readLine().split(" ");
n = Integer.parseInt(s[0]);
m = Integer.parseInt(s[1]);
k = Integer.parseInt(s[2]);
for (int i = 0; i < m; i++) {
s = br.readLine().split(" ");
int a = Integer.parseInt(s[0]);
int b = Integer.parseInt(s[1]);
int c = Integer.parseInt(s[2]);
road[i] = new Pair(a, b, c);
}
Arrays.sort(road, 0, m);
for (int i = 0; i < k; i++) {
s = br.readLine().split(" ");
int times = Integer.parseInt(s[0]);
int first = Integer.parseInt(s[1]);
int pfirst = find(first);
for (int j = 2; j <= times; j++) {
int temp = Integer.parseInt(s[j]);
int ptemp = find(temp);
if (ptemp != pfirst) {
p[ptemp] = pfirst;
cnt++;
}
}
}
//kruskal
long res = 0;
for (int i = 0; i < m; i++) {
int x = road[i].x;
int y = road[i].y;
int w = road[i].w;
x = find(x);
y = find(y);
if (x != y) {
p[x] = y;
res += w;
cnt++;
}
}
if (cnt == n - 1) System.out.println(res);
else System.out.println(-1);
}
}
public static int find(int x) {
if (p[x] != x) p[x] = find(p[x]);
return p[x];
}
}
class Pair implements Comparable<Pair> {
int x, y, w;
public Pair(int x, int y, int w) {
this.x = x;
this.y = y;
this.w = w;
}
@Override
public int compareTo(Pair pair) {
return this.w - pair.w;
}
}