hdu 1162(最小生成树kruskal)

/*

  Name: 最小生成树(kruskal) 

  Author: 

  Date: 10/04/12 19:17

*/



#include <math.h>

#include <cstdio>

#include <iostream>



using namespace std;



const int M = 5050;



int p[101], sum;

struct edge {

    int a;

    int b;

    double dis;

}e[M];

struct point {

    double x;

    double y;

}po[101];



int cmp(const void *a, const void *b) {

    if ((*(edge *)a).dis > (*(edge *)b).dis) return 1;

    return -1;

}



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];

}



double join(edge e) {

    int x, y;

    x = find(e.a);

    y = find(e.b);

    if (x != y) {

        ++sum;

        p[x] = y;

        return e.dis;

    }

    return 0;

}



double kruskal(int es, int vs) {

    double 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;

    }

}



int main() {

    int n;

    while (scanf("%d", &n) != EOF) {

        for (int i=1; i<=n; ++i) scanf ("%lf%lf", &po[i].x, &po[i].y);

        int es = 0;

        for (int i=1; i<n; ++i) {

            for (int j=i+1; j<=n; ++j) {

                e[es].dis = sqrt((po[i].x-po[j].x)*(po[i].x-po[j].x)+(po[i].y-po[j].y)*(po[i].y-po[j].y));

                e[es].a = i;

                e[es].b = j;

                ++es;

            }

        }

        sum = 1;

        double ans = kruskal(es, n);

        printf ("%.2lf\n", ans);

    }

    return 0;

}

 

你可能感兴趣的:(最小生成树)