最小生成树板子-AcWing 859. Kruskal算法求最小生成树
生活随笔
收集整理的這篇文章主要介紹了
最小生成树板子-AcWing 859. Kruskal算法求最小生成树
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目分析
來源:acwing
分析:
Kruskal算法思路:
if a和b 不連通,將這條邊加入到集合中。
第2步:時間復雜度O(m)
其中第2步,就是并查集的簡單應用。
ac代碼
#include<bits/stdc++.h> using namespace std; const int N = 2e5 + 10;int n, m; int p[N];struct Edge{int a, b, w;bool operator<(const Edge& W)const{return w < W.w;} }edges[N];int find(int x){if( p[x] != x) p[x] = find(p[x]);return p[x]; }int main(){cin >> n >> m;for(int i = 0; i < m; i ++){int a, b, w;cin >> a >> b >> w;edges[i] = {a, b, w};}sort(edges, edges + m);int res = 0, cnt = 0;for(int i = 1; i<= n; i++) p[i] = i;for(int i = 0; i < m; i++){int a = edges[i].a, b = edges[i].b, w = edges[i].w;a = find(a), b= find(b);if( a != b){p[a] =b;res += w;cnt ++; // 統計加了多少條邊}}if(cnt < n - 1) puts("impossible");else printf("%d\n", res);}題目來源
https://www.acwing.com/problem/content/861/
總結
以上是生活随笔為你收集整理的最小生成树板子-AcWing 859. Kruskal算法求最小生成树的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 最小生成树板子-AcWing 858.
- 下一篇: CSP认证201412-4最优灌溉[C+