标签:hdu1879 hdu 1879 畅通工程 最小生成树
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
畅通工程系列是做完了~~
最小生成树~两种算法prim和kruskal。我应用的后者
#include <stdio.h>
#include <algorithm>
#include <string.h>
using namespace std;
int fa[105];
struct node
{
int a,b,cost;
}c[5000];
bool cmp(node x,node y)
{
return x.cost<y.cost;
}
int find(int x)
{
if(fa[x]!=x) fa[x]=find(fa[x]);
return fa[x];
}
int main()
{
int n,x;
while(scanf("%d",&n)!=EOF&&n)
{
memset(&c,0,sizeof(&c));
for(int i=1;i<=n;i++)
fa[i]=i;
n=n*(n-1)/2;
for(int i=0;i<n;i++)
{
scanf("%d %d %d %d",&c[i].a,&c[i].b,&c[i].cost,&x);
if(x==1)
c[i].cost=0;
}
sort(c,c+n,cmp);
int sum=0;
for(int i=0;i<n;i++)
{
int x=find(c[i].a);
int y=find(c[i].b);
if(x!=y)
fa[x]=y,sum+=c[i].cost;
}
printf("%d\n",sum);
}
return 0;
}版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:hdu1879 hdu 1879 畅通工程 最小生成树
原文地址:http://blog.csdn.net/su20145104009/article/details/47027605