标签:acm 最小生成树 继续畅通工程 hdu1879 kruskal
3 1 2 1 0 1 3 2 0 2 3 4 0 3 1 2 1 0 1 3 2 0 2 3 4 1 3 1 2 1 0 1 3 2 1 2 3 4 1 0
3 1 0


/****************************************
*****************************************
* Author:Tree *
*From :http://blog.csdn.net/lttree *
* Title : 继续畅通工程 *
*Source: hdu 1879 *
* Hint : 最小生成树(MST-Prim) *
*****************************************
****************************************/
#include <stdio.h>
#include <algorithm>
using namespace std;
struct Road
{
int u,v,c;
}r[10001];
int n,m,father[10001];
bool cmp(Road r1,Road r2)
{
return r1.c<r2.c;
}
// 并查集系列函数 1-初始化 2-查找 3-合并
void Init( int n )
{
int i;
for(i=1;i<=n;++i)
father[i]=i;
}
int Find(int m)
{
while( father[m]!=m )
{ m=father[m]; }
return m;
}
void Combine( int a,int b)
{
int temp_a,temp_b;
temp_a=Find(a);
temp_b=Find(b);
if( temp_a!=temp_b )
father[temp_a]=temp_b;
}
int Kruskal( void )
{
sort(r,r+m,cmp);
Init(n);
Road rd;
int i,res;
// 构建最小生成树
res=0;
for( i=0;i<m;++i )
{
rd=r[i];
if( Find(rd.u)!=Find(rd.v) )
{
Combine(rd.u,rd.v);
res+=rd.c;
}
}
return res;
}
int main()
{
int i,start,finish,cost,iscon;
while( scanf("%d",&n) && n )
{
// 求边的数量
m = n*(n-1)/2;
for( i=0;i<m;++i )
{
scanf("%d%d%d%d",&start,&finish,&cost,&iscon);
r[i].u=start;
r[i].v=finish;
// 如果道路已经修建,消耗设置为0,不需要我们再去建立道路
if( iscon ) r[i].c=0;
else r[i].c=cost;
}
printf("%d\n",Kruskal());
}
return 0;
}
ACM-最小生成树之继续畅通工程——hdu1879,布布扣,bubuko.com
标签:acm 最小生成树 继续畅通工程 hdu1879 kruskal
原文地址:http://blog.csdn.net/lttree/article/details/27092583