#include <bits/stdc++.h> typedef long long ll; const int maxx = 200010; const int inf = 0x3f3f3f3f; using namespace std; int pre[maxx]; int n; struct node//存边权值 { int s; int e; int v; } edge[maxx]; bool cmp(node a, node b)//看情况修改 优先级给小边权还是大边权 { return a.v < b.v; } void init()//初始化 { for (int i = 0; i <= n; i++) pre[i] = i; } int getf(int a)//并查集 看两点是否在同一个图内 { if (pre[a] == a) return a; int tmp = getf(pre[a]); return pre[a] = tmp; } int Kruskal(int a, int b) //并查集合并操作,看是否在同一个图内 如果在就跳过 不在就合并 { int fa = getf(a); int fb = getf(b); if (fa != fb) { pre[fa] = fb; return 1; } else return 0; } int main() { while (~scanf("%d", &n), n) { init(); int m = (n * (n - 1)) / 2; for (int i = 1; i <= m; i++) scanf("%d%d%d", &edge[i].s, &edge[i].e, &edge[i].v); sort(edge + 1, edge + m + 1, cmp); int ans = 0; for (int i = 1; i <= m; i++) { if (Kruskal(edge[i].s, edge[i].e)) ans += edge[i].v; } printf("%d\n", ans); } return 0; }
#include <stdio.h> #include <string> #include <string.h> #include <iostream> #include <algorithm> #include <math.h> #include <queue> #include <stack> #include <map> #include <set> typedef long long ll; const int maxx = 10010; const int mod = 10007; const int inf = 0x3f3f3f3f; const double eps = 1e-8; using namespace std; struct node { int s; int e; int v; } edge[maxx]; bool cmp(node a, node b) { return a.v < b.v; } int pre[maxx]; int n, r; void init() { for (int i = 0; i <= n; i++) pre[i] = i; } int getf(int a) { if (pre[a] == a) return a; int tmp = getf(pre[a]); return pre[a] = tmp; } int Kruskal(int a, int b) { int fa = getf(a); int fb = getf(b); if (fa != fb) { pre[fa] = fb; return 1; } else return 0; } int main() { while (~scanf("%d%d", &n, &r), n) { init(); for (int i = 1; i <= r; i++) scanf("%d%d%d", &edge[i].s, &edge[i].e, &edge[i].v); sort(edge + 1, edge + r + 1, cmp); int ans = 0; for (int i = 1; i <= r; i++) { if (Kruskal(edge[i].s, edge[i].e)) ans += edge[i].v; } printf("%d\n", ans); } return 0; }