数据结构实验之图论九:最小生成树---2144

数据结构实验之图论九:最小生成树

Time Limit: 1000MS Memory Limit: 65536KB
Problem Description

 有n个城市,其中有些城市之间可以修建公路,修建不同的公路费用是不同的。现在我们想知道,最少花多少钱修公路可以将所有的城市连在一起,使在任意一城市出发,可以到达其他任意的城市。

 

Input

 输入包含多组数据,格式如下。

第一行包括两个整数n m,代表城市个数和可以修建的公路个数。(n <= 100, m <=10000)

剩下m行每行3个正整数a b c,代表城市a 和城市b之间可以修建一条公路,代价为c。

 

Output

 每组输出占一行,仅输出最小花费。

Example Input
3 2
1 2 1
1 3 1
1 0
Example Output
2
0



#include <stdio.h>
#include <stdlib.h>
int s[10005];
struct node{
int a;
int b;
int c;
}ct[10005];

int cmp(const void *x,const void *y)
{
   return (*(struct node *)x).c > (*(struct node *)y).c ? 1: -1;
}

int find(int a)
{
    if(s[a]==a)
    return a;
    else
    {
       s[a]=find(s[a]);
       return s[a];
    }
}

int join(int a,int b)
{
   int t1,t2;
   t1=find(a);
   t2=find(b);
   if(t1!=t2)
   {
      s[t2]=t1;
      return 1;
   }
  return 0;
}
int main()
{
    int n,m,i,sum,cost;
    while(~scanf("%d%d",&n,&m))
    {
       sum=0;cost=0;
       for(i=1;i<=n;i++)
       s[i]=i;
       for(i=0;i<m;i++)
       {
         scanf("%d%d%d",&ct[i].a,&ct[i].b,&ct[i].c);
       }
       qsort(ct,m,sizeof(ct[0]),cmp);
       for(i=0;i<=m;i++)
       {
         if(join(ct[i].a,ct[i].b))
         {
            sum++;
            cost+=ct[i].c;
         }
         if(sum==n-1)
         break;
       }
       printf("%d\n",cost);
    }
    return 0;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值