最小生成树 - Kruskal()

//http://acm.hdu.edu.cn/showproblem.php?pid=1233
#include <cstdio>
#include <algorithm>
using namespace std;
const int N = 105;
struct Edage
{
    int x, y, v;
} e[N * (N - 1) / 2];
int n;
int father[N];
int find(int x)
{
    if (x != father[x])
        father[x] = find(father[x]);
    return father[x];
}
bool cmp(Edage e1, Edage e2)
{
    return e1.v < e2.v;
}
int Kruskal()
{
    sort(e, e + n, cmp);
    int sum = 0;
    for (int i = 0; i < n; i++)
    {
        int x = find(e[i].x);
        int y = find(e[i].y);
        if (x != y)
        {
            sum += e[i].v;
            father[x] = y;
        }
    }
    return sum;
}
int main()
{
    while (scanf("%d", &n), n)
    {
        for (int i = 1; i <= n; i++)
            father[i] = i;
        n = n * (n - 1) / 2;
        for (int i = 0; i < n; i++)
            scanf("%d%d%d", &e[i].x, &e[i].y, &e[i].v);
        printf("%d\n", Kruskal());
    }
    return 0;
}

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