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

来源:互联网 发布:刺客信条4优化补丁 编辑:程序博客网 时间:2024/05/16 01:19

Problem Description

当前农村公路建设正如火如荼的展开,某乡镇政府决定实现村村通公路,工程师现有各个村落之间的原始道路统计数据表,表中列出了各村之间可以建设公路的若干条道路的成本,你的任务是根据给出的数据表,求使得每个村都有公路连通所需要的最低成本。

Input

连续多组数据输入,每组数据包括村落数目N(N <= 1000)和可供选择的道路数目M(M <= 3000),随后M行对应M条道路,每行给出3个正整数,分别是该条道路直接连通的两个村庄的编号和修建该道路的预算成本,村庄从1~N编号。 

Output

输出使每个村庄都有公路连通所需要的最低成本,如果输入数据不能使所有村庄畅通,则输出-1,表示有些村庄之间没有路连通。 

Example Input

5 81 2 121 3 91 4 111 5 32 3 62 4 93 4 44 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