并查集。
#include <cstdio>
#include <cstring>
#include <cstdlib> #define MAXN 10005
#define INF 0xffffff typedef struct {
int c, s, e;
} edge_st; edge_st edges[];
int pre[MAXN];
int deg[MAXN];
int n, m, ans; int comp(const void *a, const void *b) {
return ((edge_st *)b)->c - ((edge_st *)a)->c;
} int find(int x) {
return x==pre[x] ? x:pre[x]=find(pre[x]);
} void merge(int i) {
int a, b; a = find(edges[i].s);
b = find(edges[i].e);
if (a != b) {
if (deg[a] == ) {
pre[a] = b;
ans += edges[i].c;
} else if (deg[b] == ) {
pre[b] = a;
ans += edges[i].c;
}
} else {
if (deg[a] == ) {
++deg[a];
ans += edges[i].c;
}
}
} int main() {
int i; while (scanf("%d %d", &n, &m)!=EOF && (n||m)) {
for (i=; i<m; ++i)
scanf("%d %d %d", &edges[i].s, &edges[i].e, &edges[i].c);
qsort(edges, m, sizeof(edge_st), comp);
for (i=; i<n; ++i)
pre[i] = i;
memset(deg, , sizeof(deg));
ans = ;
for (i=; i<m; ++i)
merge(i);
printf("%d\n", ans);
} return ;
}