uva11631 - Dark roads

#include <cstdio>
#include <cstring>
#include <cstdlib>

using namespace std;

const int N = 200010;

int id[N], u[N], v[N], w[N];
int m, n;
int p[N];

int cmp(const void *a, const void *b);
int find(int x);
int Union(int e);

int main()
{
    int sum;
    int cost;

#ifndef ONLINE_JUDGE
    freopen("uva_in.txt", "r", stdin);
#endif

    while (scanf("%d%d", &m, &n) == 2) {
        if (m == 0 && n == 0) break;
        
        sum = 0;
        for (int i = 0; i < n; i++) {
            id[i] = i;
            scanf("%d%d%d", &u[i], &v[i], &w[i]);
            sum += w[i];
        }

        memset(p, -1, sizeof(p));

        qsort(id, n, sizeof(int), cmp);
        cost = 0;
        for (int i = 0; i < n; i++) {
            cost += Union(id[i]);
        }

        printf("%d\n", sum - cost);
    }
    return 0;
}

int cmp(const void *a, const void *b)
{
    int *pa = (int*)a;
    int *pb = (int*)b;

    return w[*pa] - w[*pb];
}

int find(int x)
{
    return p[x] < 0 ? x : (p[x] = find(p[x]));
}

int Union(int e)
{
    int a = u[e];
    int b = v[e];

    int pa = find(a), pb = find(b);
    
    if (pa != pb) {
        p[pb] = pa;
        return w[e];        
    }

    return 0;
}

你可能感兴趣的:(uva11631 - Dark roads)