51 nod 1212 基础MST

来源:互联网 发布:淘宝品牌调性分怎么查 编辑:程序博客网 时间:2024/05/18 00:37

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

直接上代码:裸的最小生成树.

#include<iostream>#include<algorithm>#include<stdio.h>#include<cmath>#define max1 1005#define max2 50005using namespace std;struct edge{    int be,en,cost;};edge e[max2];int node[max1];int sum=0;int find(int x){    while(x!=node[x])        x=node[x];    return x;}bool cmp(edge a,edge b){    return a.cost<b.cost;}int main(){    int n,m;    cin>>n>>m;    for(int x=1;x<=n;x++)        node[x]=x;    for(int x=0;x<m;x++)        scanf("%d%d%d",&e[x].be,&e[x].en,&e[x].cost);        sort(e,e+m,cmp);        for(int x=0;x<m;x++)        {            int bx=find(e[x].be);            int by=find(e[x].en);            if(bx!=by)            {                sum+=e[x].cost; node[bx]=by;            }        }        cout<<sum;}
原创粉丝点击