1004
题意:将一些镇子连起来,求最短距离
用kruskal求最小生成树
代码:
#include <iostream> #include <algorithm> using namespace std; const int N = 105; int father[N]; int find(int x) { if (x != father[x]) father[x] = find(father[x]); return father[x]; } struct edge { int x, y, v; }e[N*(N - 1) / 2]; int cmp(edge e1, edge e2) { return e1.v<e2.v; } int main() { int n; while (cin >> n&&n) { for (int i = 0; i <= n; ++i) father[i] = i; n = n*(n - 1) / 2; for (int i = 0; i<n; i++) cin>>e[i].x>>e[i].y>>e[i].v; sort(e, e + n, cmp); int ans = 0; for (int i = 0; i < n; ++i) { int x = find(e[i].x); int y = find(e[i].y); if (x != y) { ans += e[i].v; father[x] = y; } } cout << ans << endl; } return 0; }