最小生成树模板

Posted leonard-

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了最小生成树模板相关的知识,希望对你有一定的参考价值。

Kruskal:

 1 typedef long long LL;
 2 const int N=123;
 3 int Father[N];
 4 struct node{
 5     int u,v;
 6     LL cost;
 7 }p[N];
 8 int n,m;
 9 
10 bool cmp(node x,node y){
11     return x.cost<y.cost;
12 }
13 
14 void init(){
15     for(int i=0;i<N;i++) Father[i]=i;
16 }
17 
18 int Find(int x){
19     return x==Father[x]?x:Father[x]=Find(Father[x]);
20 }
21 
22 void Union(int x,int y){
23     int fx=Find(x),fy=Find(y);
24     if(fx!=fy){
25         Father[fx]=fy;
26     }
27 }
28 
29 LL kruskal(){
30     sort(p+1,p+1+n,cmp);
31     LL res=0;
32     for(int i=1;i<=n;i++){
33         if(Find(p[i].u)!=Find(p[i].v)){
34             Union(p[i].u,p[i].v);
35             res+=p[i].cost;
36         }
37     }
38     return res;
39 }

 

以上是关于最小生成树模板的主要内容,如果未能解决你的问题,请参考以下文章

最小生成树模板

Highways——最小生成树模板题(求距离)

牛客-道路建设——最小生成树模板题

还是畅通工程——最小生成树模板题

3366 模板最小生成树(Kruskal)

Agri-Net POJ 1258(最小生成树模板)