Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 32507 Accepted Submission(s): 14622
3 1 2 1 1 3 2 2 3 4 4 1 2 1 1 3 4 1 4 1 2 3 3 2 4 2 3 4 5 0
3 5Huge input, scanf is recommended.HintHint
不得不说,还好当时认真学了并查集,仔细想了。虽说现在忘了不少,但是一看代码还能想起来,也知道每一行代码的意思。
#include<stdio.h> #include<iostream> #include<algorithm> using namespace std; int pre[110],n; struct node{ int u, v, w; }; node edge[10010]; int cmp(node a, node b){ return a.w < b.w; } void init(){ int i; for(i = 1; i <= n; ++i){ pre[i] = i; } } int find(int x){ int r = x; while(pre[r] != r) r = pre[r]; pre[x] = r; return r; } bool join(int x, int y){ int fx = find(x); int fy = find(y); if(fx != fy){ pre[fx] = fy; return true; } return false; } int main(){ while(~scanf("%d", &n), n){ int i, sum = 0; for(i = 0; i < n * (n-1) / 2; ++i){ scanf("%d%d%d", &edge[i].u, &edge[i].v, &edge[i].w); } init(); sort(edge, edge + n * (n-1) / 2, cmp); for(i = 0; i < n * (n-1) / 2; ++i){ if(join(edge[i].u, edge[i].v)) sum += edge[i].w; } printf("%d\n", sum); } return 0; }