码迷,mamicode.com
首页 > 其他好文 > 详细

最小生成树模板

时间:2018-03-20 13:54:00      阅读:148      评论:0      收藏:0      [点我收藏+]

标签:init   color   i++   pre   ==   nod   def   fat   post   

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 }

 

最小生成树模板

标签:init   color   i++   pre   ==   nod   def   fat   post   

原文地址:https://www.cnblogs.com/Leonard-/p/8608578.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!