HZNU-ACM寒假集训Day8小结

最小生成树(无向图)

   Kruskal   

   给所有边按从小到大排序 形成环则不选择(利用并查集)

   P1546 最短网络   https://www.luogu.com.cn/problem/P1546

   

#include<iostream>
#include<cstdio>
#include<string>
#include<algorithm>
typedef long long ll;
using namespace std;

struct Node {
    int x, y, w;
    friend bool operator < (const Node& a, const Node& b) {
        return a.w < b.w;
    }
};

Node a[200002];
int pre[200002];

int Find(int x) {
    return pre[x] == x ? x : pre[x] = Find(pre[x]);
}

int main() {
    int n, k, cnt = 0;
    scanf("%d", &n);
    for (int i = 0; i < n; i++) {
        pre[i] = i;
        for(int j=0;j<n;j++){
        scanf("%d", &k);
          if (j > i) {   //矩阵只需判断一半
              a[cnt].x = i;
              a[cnt].y = j;
              a[cnt++].w = k;
          }
        }
    }
    sort(a, a + cnt);
    int ans = 0;
    int p = 0;
    for (int i = 0; i <cnt; i++) {
        if (Find(a[i].x) != Find(a[i].y)) {
            ans += a[i].w;
            pre[Find(a[i].x)] = a[i].y;
            p++;
            if (p == n - 1) break;
        }
    }
    printf("%d\n", ans);
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/hznumqf/p/12262669.html