1. 程式人生 > >【模版】最小生成樹Kruskal模版

【模版】最小生成樹Kruskal模版

algo using () clu 生成樹 code mes log 連通圖

最小生成樹簡單來說就是在一個有$n$條邊的有權無向連通圖中選出$n-1$條邊,使圖連通並且這$n-1$條邊的邊權和最小。

Kruskal算法是用一種貪心的思想,先將所有的邊按邊權排序,按邊權從小到大順序枚舉邊,如果起點和終點不在一個集合,就選這條邊,並將起點和終點合並成一個集合;反之則不選此邊。集合可以用並查集維護。

(以上內容純屬瞎編,若要系統學習請百度)

下面是模版

//最小生成樹(Kruskal)模版 
//By LC  2017.2.19整理 
#include <cstdio>
#include <algorithm>
using namespace
std; const int M = 200005, N = 5005; struct Node { int u, v, w; }a[M]; int t[N]; bool cmp(Node x, Node y) { return x.w < y.w; } int Find(int i) { if(t[i] == i) return i; else return t[i] = Find(t[i]); } int main() { int n, m, i, j, ans = 0; scanf(
"%d%d", &n, &m); for(i = 1; i <= m; i++) scanf("%d%d%d", &a[i].u, &a[i].v, &a[i].w); for(i = 1; i <= n; i++) t[i] = i; sort(a+1, a+1+m, cmp); for(i = j = 1; i <= m && j <= n; i++) { int ss = Find(a[i].u), tt
= Find(a[i].v); if(ss != tt) { ans += a[i].w; t[ss] = tt; j++; } } printf("%d", ans); return 0; }

【模版】最小生成樹Kruskal模版