hdu1879(kruskal求最小生成树)

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1879

源代码:

#include<iostream>
#include<cstdlib>
#include<cstdio>
#include<algorithm>

using namespace std;

typedef struct Edge
{
 int start,end,weight,flag;
}edge;
edge e[5000];
int city[101];

bool comp(const edge &a,const edge &b)
{
 if(a.weight<b.weight)return 1;
 return 0;
}
int find_set(int n)
{
 if(city[n]==-1)return n;
 else return city[n]=find_set(city[n]);
}
bool Merge(int s1,int s2)
{
 int r1=find_set(s1);
 int r2=find_set(s2);
 if(r1==r2)return 0;
 if(r1<r2)city[r2]=r1;
 else city[r1]=r2;
 return 1;
}
int main()
{
 int n;
 while(scanf("%d",&n)!=EOF&&n)
 {
  int m=n*(n-1)/2;
  int sum=0,count=0,i;
  memset(city,-1,sizeof(city));
  for(i=0;i<m;i++)
  {
   scanf("%d%d%d%d",&e[i].start,&e[i].end,&e[i].weight,&e[i].flag);
   if(e[i].flag==1)e[i].weight=0;
  }
  sort(e,e+m,comp);
  for(i=0;i<m;i++)
  {
   if(Merge(e[i].start,e[i].end))
   {
    count++;
    sum+=e[i].weight;
   }
   if(count==n-1)break;
  }
  printf("%d\n",sum);
 }
 return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值