1 6 4 3 1 4 2 2 6 1 2 3 5 3 4 33 2 1 2 2 1 3 3 4 5 6
1
开始判断sum值,wa了,看题目(0 <= c <= 1000),并不能从sum=0判断的=。=
#include <iostream> #include <algorithm> #include <cstdio> using namespace std; #pragma warning(disable : 4996) #define MAX 25005 typedef struct edge { int x, y; int w; }edge; edge e[MAX]; int father[MAX], ranks[MAX]; bool cmp(edge a,edge b) { return a.w < b.w; } void Make_Set(int n) { for(int i = 1; i <= n; i++) { father[i] = i; ranks[i] = 0; } } int Find_Set(int x) { if(x != father[x]) father[x] = Find_Set(father[x]); return father[x]; } void Merge_Set(int x, int y) { x = Find_Set(x); y = Find_Set(y); if(x == y) return; if(ranks[x] > ranks[y]) { father[y] = x; } else if(ranks[x] < ranks[y]) { father[x] = y; } else { ranks[y]++; father[x] = y; } } int main() { freopen("in.txt", "r", stdin); int t, i, j, n, m, k, sum, x, y, w, v; scanf("%d", &t); while (t--) { scanf("%d %d %d", &n, &m, &k); Make_Set(n); for(i = 0; i < m; i++) { scanf("%d %d %d", &x, &y, &w); e[i].x = x; e[i].y = y; e[i].w = w; } sort(e, e + m, cmp); for(i = 1; i <= k; i++) { scanf("%d", &v); if(v == 2) { cin >> x >> y; Merge_Set(x, y); } else { scanf("%d %d", &x, &y); Merge_Set(x, y); x = y; for(j = 2; j < v; j++) { scanf("%d", &y); Merge_Set(x, y); x = y; } } } sum = 0; for(i = 0; i < m; i++) { x = Find_Set(e[i].x); y = Find_Set(e[i].y); if(x != y) { Merge_Set(x, y); sum += e[i].w; } } int count = 0; for(i = 1; i <= n; i++) { if(i == father[i]) { count++; } } if(count > 1) { printf("-1\n"); } else { printf("%d\n", sum); } } return 0; }