HDU - 1233 (最小生成树)

AC代码:

#include <cstdio>
#include<algorithm>
using namespace std;
const int N = 110;
struct node{
    int u, v, w;
}q[N*N];
int pre[N];
int n, m;
void init(){
    for(int i = 1; i<= n; i++){
        pre[i] = i;
    }
}
int Find(int x){
    if(x != pre[x]) pre[x] = Find(pre[x]);
    return pre[x];
}
void join(int x, int y){
    int tx = Find(x);
    int ty = Find(y);
    if(tx != ty) pre[ty] = tx;
}
bool cmp(node a, node b){
    return a.w < b.w;
}
int Kru(){
    int ans = 0;
    sort(q+1, q+1+m, cmp);
    for(int i = 1; i <= m; i++){
        if(Find(q[i].u) != Find(q[i].v)){
            join(q[i].u, q[i].v);
            ans += q[i].w;
        }
    }
    return ans;
}
int main(){
    #ifdef ONLINE_JUDGE
    #else
        freopen("in.txt", "r", stdin);
    #endif
    int a, b, c;
    while(scanf("%d", &n) && n){
        init();
        m = n*(n - 1)/2;
        for(int i = 1; i<= m; i++){
            scanf("%d%d%d", &q[i].u, &q[i].v, &q[i].w);
        }
        int ans = Kru();
        printf("%d\n", ans);
    }
    return 0;
}


posted on 2018-10-22 21:41  坤sir  阅读(161)  评论(0编辑  收藏  举报

导航