无向图最小生成树

10 篇文章 0 订阅
7 篇文章 0 订阅

问题

N个点M条边的无向连通图,每条边有一个权值,求该图的最小生成树。

Input

第1行:2个数N,M中间用空格分隔,N为点的数量,M为边的数量。(2 <= N <= 1000, 1 <= M <= 50000)
第2 - M + 1行:每行3个数S E W,分别表示M条边的2个顶点及权值。(1 <= S, E <= N,1 <= W <= 10000)

Output

输出最小生成树的所有边的权值之和。

题解

prim 优先队列+邻接链表

//62 ms 3584 KB

#include<stdio.h>
#include<queue>
#include<vector>
#define INF 0x3f3f3f3f
#define MAX_V 1002
#define MAX_E 50002
using namespace std;
typedef pair<int,int> P;//fiest->cost  second->id
struct edge{int to,cost;};
vector<edge> G[MAX_V];
int V,E;
int used[MAX_V];

int prim(){
    fill(used,used+V+1,false);
    priority_queue<P,vector<P>,greater<P> > que;
    que.push({0,1});
    int res=0;

    while(!que.empty()){
        P p=que.top();que.pop();
        int v=p.first,f=p.second;
        if(used[f]) continue;
        used[f]=true;
        res+=v;

        for(int i=0;i<G[f].size();i++)
            if(!used[G[f][i].to])
                que.push({G[f][i].cost,G[f][i].to});
    }
    return res;
}

int main()
{
    int x,y,v;
    while(~scanf("%d%d",&V,&E)){
        for(int i=0;i<E;i++){
            scanf("%d%d%d",&x,&y,&v);
            G[x].push_back({y,v});
            G[y].push_back({x,v});
        }
        printf("%d\n",prim());
        for(int i=1;i<=V;i++) G[i].clear();
    }
    return 0;
}

Kruskal

//78 ms 2312 KB

#include<stdio.h>
#include<algorithm>
#define INF 0x3f3f3f3f
#define MAX_V 1002
#define MAX_E 50002
using namespace std;
struct edge{int from,to,cost;};
edge es[MAX_E];
int par[MAX_V];
int E,V;

void init(int n){for(int i=0;i<=n;i++) par[i]=i;}
int find(int x){return x==par[x]?x:par[x]=find(par[x]);}
void unite(int x,int y){par[find(y)]=find(x);}
bool same(int x,int y){return find(x)==find(y);}

bool cmp(edge x,edge y){return x.cost<y.cost;};

int kruskal(){
    sort(es,es+E,cmp);
    init(V);
    int res=0;

    for(int i=0;i<E;i++){
        int x=es[i].from,y=es[i].to;
        if(!same(x,y)){
            unite(x,y);
            res+=es[i].cost;
        }
    }
    return res;
}

int main()
{
    while(~scanf("%d%d",&V,&E)){
        for(int i=0;i<E;i++)
            scanf("%d%d%d",&es[i].from,&es[i].to,&es[i].cost);
        printf("%d\n",kruskal());
    }
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值