1090: 最小生成树(模版 kruskal算法 )

来源:互联网 发布:上市公司数据在哪里查 编辑:程序博客网 时间:2024/05/31 19:48

1090: [视频]最小生成树(模版 kruskal算法 元问题by scy)
时间限制: 1 Sec 内存限制: 128 MB
提交: 313 解决: 97
[提交][状态][讨论版]
题目描述

【题目描述】
一个有n个点的连通无向图,有m条无向边,每条边有一个长度c,
如果连接所有点,只需要从m条无向边中选n-1条,为什么?
现在要求这n-1条边的长度和最小。

以上就是最小生成树的概念。

【输入格式】
第一行输入 n和 m (1<=n<=1000,n-1<=m<=50 0000)
下来 N 行,每行三个数 x,y,c,表示点 x 和 点 y 有一条距离为 c 的无向边。0

#include<iostream>#include<algorithm>using namespace std;struct node{int x,y,len;};struct node N[500005];int father[1100];int n,m;bool cmp(struct node a,struct node b){    return a.len<b.len;}int find_father(int x){    if (father[x]==x) return x;    else    {        father[x]=find_father(father[x]);        return  father[x];    }}int main(){    int sum_len=0,total=0;    cin>>n>>m;    for (int i=1;i<=m;i++)    {        cin>>N[i].x>>N[i].y>>N[i].len;    }    sort(N+1,N+m+1,cmp);    for (int i=0;i<=n;i++)        father[i]=i;    for (int i=1;i<m;i++)    {        int fx=find_father(N[i].x);        int fy=find_father(N[i].y);        if (fx!=fy)        {            sum_len+=N[i].len;            father[fx]=fy;            total++;            if (total==n-1)                break;        }    }    cout<<sum_len<<endl;    return 0;}
原创粉丝点击