数据结构-图基础-kruskal

Posted hexiang|

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了数据结构-图基础-kruskal相关的知识,希望对你有一定的参考价值。

首先利用结构体存边,排序(快排,或者建堆),遍历所有边,利用并查集判断边两个端点是否在同一个集合中。

acwing-859

 

 

#include<bits/stdc++.h>
using namespace std;
const int N = 100010;
struct edge{
    int a, b, c;
    bool operator<(const edge& w){
        return c < w.c;
    }
}ed[2 * N];
int p[N], n, m;
//并查集
int find(int x){ if(x == p[x]) return x; else return p[x] = find(p[x]); } int kruskal(){ for(int i = 1; i <= n; i++) p[i] = i; sort(ed, ed + m); int ans = 0, cnt = 0; for(int i = 0; i < m; i++){ int a = ed[i].a, b = ed[i].b; if(find(a) != find(b)){ p[find(a)] = find(b); ans += ed[i].c; cnt++; } } if(cnt == n - 1) return ans; else return -1; } int main(){ cin >> n >> m; for(int i = 0; i < m; i++){ int a, b, c; cin >> a >> b >> c; ed[i] = {a, b, c}; } int ans = kruskal(); if(ans == -1) printf("impossible"); else printf("%d\\n", ans); return 0; }

 

以上是关于数据结构-图基础-kruskal的主要内容,如果未能解决你的问题,请参考以下文章