(kruskal最小生成树)数据结构实验之图论六:村村通公路

Problem Description
当前农村公路建设正如火如荼的展开,某乡镇政府决定实现村村通公路,工程师现有各个村落之间的原始道路统计数据表,表中列出了各村之间可以建设公路的若干条道路的成本,你的任务是根据给出的数据表,求使得每个村都有公路连通所需要的最低成本。
Input
连续多组数据输入,每组数据包括村落数目N(N <= 1000)和可供选择的道路数目M(M <= 3000),随后M行对应M条道路,每行给出3个正整数,分别是该条道路直接连通的两个村庄的编号和修建该道路的预算成本,村庄从1~N编号。 
Output
输出使每个村庄都有公路连通所需要的最低成本,如果输入数据不能使所有村庄畅通,则输出-1,表示有些村庄之间没有路连通。 
Example Input
5 8
1 2 12
1 3 9
1 4 11
1 5 3
2 3 6
2 4 9
3 4 4
4 5 6
Example Output
19





#include <iostream>
#include <stdio.h>
#include <cstring>
#include <algorithm>

using namespace std;

int father[1005];


struct edge
{
    int s;
    int e;
    int w;
}ed[3005];

int find_dad(int a)
{
    if(father[a]==a)
        return a;
    return father[a]=find_dad(father[a]);
}

int union_node(int x,int y)
{
    int x1=find_dad(x);
    int y1=find_dad(y);

    if(x1!=y1)
    {
        father[x1]=y1;
        return 1;
    }
    return 0;

}

bool cmp(edge a,edge b)
{
    return a.w<b.w;
}



int main()
{
   int n,m;
    while(scanf("%d%d",&n,&m)!=EOF)
   {

       int sum=0;
       int acount=0;
       for(int i=1;i<=m;i++)   //读入
       {
           cin>>ed[i].s>>ed[i].e>>ed[i].w;
       }

       for(int i=1;i<=n;i++)   //并查集初始化
        father[i]=i;



       sort(ed+1,ed+m+1,cmp);

       for(int i=1;i<=m;i++)
       {
           if(union_node(ed[i].s,ed[i].e))
           {
               sum+=ed[i].w;
               acount++;
           }
            if(acount==n-1)break;
       }



       if(acount!=n-1)cout<<-1<<endl;    //!!!!!!!!!!!!!!!

       else cout<<sum<<endl;


   }



    return 0;
}



















  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值