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

最小生成树

时间:2018-07-08 23:17:38      阅读:220      评论:0      收藏:0      [点我收藏+]

标签:sort   最小生成树   names   生成树   class   cti   return   ons   for   

备忘:优化prim


prim

未优化
#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<ctime>
#include<cstdlib>
#include<queue>
using namespace std;

const int INF=999999999;
int n,m;
int map[1005][1005];
int book[1005]= {0};
int ans=0;

struct uct1 {
    int to;
    int val;
} near[100005];
int nearn=0;

int main() {
    for(int i=0; i<1005; i++) {
        for(int j=0; j<1005; j++) {
            map[i][j]=INF;
        }
    }
    cin>>n>>m;
    for(int i=1; i<=m; i++) {
        int t1,t2,t3;
        scanf("%d%d%d",&t1,&t2,&t3);
        map[t1][t2]=t3;
        map[t2][t1]=t3;
    }

    int note=1;
    for(int i=1;i<=n-1;i++) {
        book[note]=1;
        for(int j=1; j<=n; j++) {
            if(map[note][j]<=INF&&book[j]==0) {
                near[nearn].val=map[note][j];
                near[nearn].to=j;
                nearn++;
            }
        }
        int minn=INF;
        for(int j=0;j<nearn;j++){
            
            if(near[j].val<minn&&book[near[j].to]==0){
                minn=near[j].val;
                note=near[j].to;
            }
        }
        
        ans+=minn;
    }
    cout<<ans;
    return 0;
}

kruskal

#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<ctime>
#include<cstdlib>
#include<queue>
using namespace std;

const int INF=999999999;
int n,m;
int fa[100005];
int ans=0;

struct uct1{
    int from,to,val;
}edge[100005];

bool cmp(uct1 x,uct1 y){
    return x.val<y.val;
}

int getfa(int note){
    
    if(fa[note]==note){
        return note;
    }else{
        fa[note]=getfa(fa[note]);
        return fa[note];
    }
}

int main() {
    cin>>n>>m;
    for(int i=1; i<=m; i++) {
        int t1,t2,t3;
        scanf("%d%d%d",&t1,&t2,&t3);
        edge[i].from=t1;
        edge[i].to=t2;
        edge[i].val=t3;
    }
    
    sort(edge+1,edge+1+m,cmp);
    for(int i=1;i<=n;i++){
        fa[i]=i;
    }
    int now=0;
    for(int i=1;i<=n-1;i++){
        now++;
        int fafrom=getfa(edge[now].from);
        int fato=getfa(edge[now].to);
        if(fafrom!=fato){
            fa[fato]=fafrom;
            
            ans+=edge[now].val;
        }else{
            i--;
        }
    }
    cout<<ans;
    return 0;
}

最小生成树

标签:sort   最小生成树   names   生成树   class   cti   return   ons   for   

原文地址:https://www.cnblogs.com/sun123zxy/p/mst.html

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