hdu 1863(最小生成树kruskal)

/*
  Name: hdu1863畅通工程 
  Author: Try86
  Date: 10/04/12 12:43
  Description: 最小生成树(kruskal) 
*/
#include <cstdio>
#include <iostream>

using namespace std;

const int M = 5050;

int p[M], sum; //sum统计顶点个数 
struct edge {
    int a;
    int b;
    int w;
}e[M];

int cmp(const void *a, const void *b) {
    return (*(edge *)a).w - (*(edge *)b).w;
} 

void init(int vs) {
    for (int i=1; i<=vs; ++i) p[i] = i;
    return ;
}

int find(int v) {
    if (p[v] != v) p[v] = find(p[v]);
    return p[v];
}

int join(edge e) {
    int x, y;
    x = find(e.a);
    y = find(e.b);
    if (x != y) {
        ++sum;
        p[x] = y;
        return e.w;
    }
    return 0;
}

int kruskal(int es, int vs) {
    int ans = 0;
    init(vs);
    qsort(e, es, sizeof(edge), cmp);
    for (int i=0; i<es; ++i) {
        ans += join(e[i]);
        if (sum == vs) return ans;
    }
    if (sum < vs) return -1;
}

int main() {
    int n, m;
    while (scanf("%d%d", &n, &m), n) {
        sum = 1;
        for (int i=0; i<n; ++i) scanf ("%d%d%d", &e[i].a, &e[i].b, &e[i].w);
        int ans = kruskal(n, m);
        if (ans == -1) printf ("?\n");
        else printf ("%d\n", ans);
    }
    return 0;
}

 

posted on 2012-04-10 12:47  Try86  阅读(904)  评论(0编辑  收藏  举报