敢敢单单,不过我都这样了,还死在输入上一次,它竟然真的有0这个样例
#include <bits/stdc++.h> using namespace std; const int N = 110; struct Edge{ int from, to, weight; }edge[N * N]; int pre[N]; int n, num; bool cmp(Edge x, Edge y){ return x. weight < y. weight; } void addedge(int u, int v, int w){ edge[num] = {u, v, w}; num ++; } int find(int x){ if(x == pre[x]) return x; int temp = pre[x]; pre[x] = find(temp); return pre[x]; } bool join(int x, int y){ int f1 = find(x), f2 = find(y); if(f1 != f2){ pre[f2] = f1; return true; } return false; } int kruskal(){ int ans = 0; int count = 0; sort(edge, edge + num, cmp); for(int i = 0; i < num; i ++){ if(join(edge[i]. from, edge[i]. to)){ ans += edge[i]. weight; count ++; } if(count == n - 1) break; } return ans; } int main(){ while(scanf("%d", &n) && n){ num = 0; for(int i = 1; i <= n; i ++) pre[i] = i; int a, b, c; for(int i = 1; i <= n * (n - 1) / 2; i ++){ scanf("%d%d%d", &a, &b, &c); addedge(a, b, c); } cout << kruskal() << endl; } return 0; }