最小生成树-Kruskal

#include <bits/stdc++.h>

using namespace std;
const int maxn = 1e6 + 10;
char s[maxn], s2[maxn];
int t, n, m, x, cnt, sum;
int f[555];
typedef long long ll;
typedef long double ld;
typedef struct node {
    int u, v, w;
} node;
node edge[555];
void FastSort(int l, int r) {
    if(l >= r) {
        return;
    }
    node x = edge[l];
    int i = l, j = r;
    while(i < j) {
        while(i < j && edge[j].w >= x.w) {
            j--;
        }
        edge[i] = edge[j];
        while(i < j && edge[i].w <= x.w) {
            i++;
        }
        edge[j] = edge[i];
    }
    edge[i] = x;
    FastSort(l, i - 1);
    FastSort(i + 1, r);
}
int getf(int x) {
    return x == f[x] ? x : getf(f[x]);
}
bool Merge(int u, int v) {
    int x = getf(u);
    int y = getf(v);
    if(x != y) {
        f[y] = x;
        return 1;
    }
    return 0;
}
void Kruskal() {
    for(int i = 1; i <= m; i++) {
        if(Merge(edge[i].u, edge[i].v)) {
            cnt++;
            sum += edge[i].w;
        }
        if(cnt == n - 1) {
            break;
        }
    }
}
int main() {
    while(~scanf("%d %d", &n, &m)) {
        for(int i = 1; i <= m; i++) {
            scanf("%d %d %d", &edge[i].u, &edge[i].v, &edge[i].w);
        }
        FastSort(1, m);
        for(int i = 0; i <= n; i++) {
            f[i] = i;
        }
        cnt = sum = 0;
        Kruskal();
        if(cnt == n - 1) {
            printf("%d\n", sum);
        } else {
            printf("-1\n");
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qwqwdqwqwe/article/details/80356040