CCF-CSP题解 201412-4 最优灌溉

\(kruskal\),有兴趣\(heap\_prim\)。

#include <bits/stdc++.h>

using namespace std;

struct tEdge {
    int a, b, c;
    bool operator < (const tEdge &y) const {
        return c < y.c;
    }
};
tEdge edge[100005];

int fa[1005];

int father(int x) {return (fa[x] == x) ? x : (fa[x] = father(fa[x]));}

bool combine(int x, int y) {
    int fx = father(x), fy = father(y);
    if (fx != fy) {fa[fx] = fy; return true;}
    return false;
}

int main() {
    int n, m;
    scanf("%d%d", &n, &m);

    for (int i = 0; i < m; ++i) scanf("%d%d%d", &edge[i].a, &edge[i].b, &edge[i].c);

    sort(edge, edge + m);

    for (int i = 1; i <= n; ++i) fa[i] = i;

    int ans = 0;
    for (int i = 0, k = 0; k < n - 1; ++i)
        if (combine(edge[i].a, edge[i].b) == true) {++k; ans += edge[i].c;}

    printf("%d", ans);

    return 0;
}
上一篇:CCF 201909-2 小明种苹果(续) python


下一篇:中国大学生计算机系统与程序设计竞赛 CCF-CCSP-2017 串行调度(serial)