首页 > 代码库 > 最小生成树(模板)

最小生成树(模板)

prim模板:

 1 int prim(){
 2     for(int i = 1; i <= n; i ++){
 3         mincost[i] = cost[1][i];
 4         vis[i] = false;
 5     }
 6     mincost[1] = 0;
 7     int res = 0;
 8     while(true){
 9         int v = -1;
10         for(int i = 1; i <= n; i ++){
11             if(!vis[i] && (v == -1 || mincost[i] < mincost[v]))
12                 v = i;
13         }
14         if(v == -1) break;
15         vis[v] = true;
16         res += mincost[v];
17         for(int i = 1; i <= n; i ++){
18             mincost[i] = min(mincost[i], cost[i][v]);
19         }
20     }

 

 

kruscal模板

 1 void init(){
 2     for(int i = 0; i < maxn; i ++){
 3         fa[i] = i;
 4     }
 5     weight = 0;
 6 }
 7 
 8 struct Nod{
 9     int l, r, w;
10 }nod[maxn];
11 bool cmp(Nod a, Nod b){
12     return a.w < b.w;
13 }
14 int find(int x){
15     return x = (fa[x] == x)? x : find(fa[x]);
16 }
17 void uni(int x, int y){
18     int a = find(x);
19     int b = find(y);
20     if(a != b){
21         fa[a] = b;
22     }
23 }
24 void kruscal(){
25     sort(nod, nod+cnt, cmp);
26     for(int i = 0; i < cnt; i ++){
27         if(find(nod[i].l) != find(nod[i].r)){
28             weight += nod[i].w;
29             uni(nod[i].l, nod[i].r);
30         }
31     }
32     printf("%d\n",weight);
33 }

 

使用优先队列的kruscal模板

 1 struct Nod{
 2     int l, r, w;
 3 }edg;
 4 bool operator < (Nod a, Nod b){
 5     return a.w > b.w;
 6 }
 7 int find(int x){
 8     return fa[x] = (fa[x] == x) ? x : find(fa[x]);
 9 }
10 int kruscal(){
11     int sum = 0;
12     while(que.size()){
13         edg = que.top();
14         que.pop();
15         int a = find(edg.l);
16         int b = find(edg.r);
17         if(a != b){
18             fa[a] = b;
19             sum += edg.w;
20         }
21     }
22     return sum;
23 }

 

最小生成树(模板)