题目链接:HDU 1863 畅通工程
Kruskal + 并查集,这题好像没什么好说的。。
#include <iostream> #include <algorithm> using namespace std; const int MAX_M = 100 + 10; const int MAX_N = (MAX_M * (MAX_M - 1)) >> 1; int n,m,ans,sum; int u[MAX_N],v[MAX_N],w[MAX_N],p[MAX_M],r[MAX_N]; int cmp(int i,int j) { return w[i] < w[j]; } int _find(int x) { return x == p[x] ? x : (p[x] = _find(p[x])); } int main() { while(cin >> n >> m , n) { ans = 0; for(int i = 1;i <= m;i++) p[i] = i; for(int i = 1;i <= n;i++) { cin >> u[i] >> v[i] >> w[i]; r[i] = i; } sort(r + 1,r + n + 1,cmp); int a,b; for(int i = 1;i <= n;i++) { a = _find(u[r[i]]); b = _find(v[r[i]]); if(a != b) { p[a] = b; m--; ans += w[r[i]]; } } if(m == 1) cout << ans << endl; else cout << "?" << endl; } return 0; }