3 1 2 1 1 3 2 2 3 4 4 1 2 1 1 3 4 1 4 1 2 3 3 2 4 2 3 4 5 0
3 5 Huge input, scanf is recommended.
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1233
解题思路:裸的最小生成树,克鲁斯卡尔,边权值排序。
代码例如以下:
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
#define inf 1e9
const int maxn=10005;
int fa[maxn];
struct EG
{
int x,y,w;
}eg[maxn];
void get_fa()
{
for(int i=0;i<=maxn;i++)
fa[i]=i;
}
int find(int x)
{
return x==fa[x]?x:find(fa[x]);
}
void Union(int a,int b)
{
int a1=find(a);
int b1=find(b);
if(a1!=b1)
fa[a1]=b1;
}
int cmp(EG a,EG b)
{
return a.w<b.w;
}
int main(void)
{
int a,b,w,n;
while(scanf("%d",&n)!=EOF&&n)
{
get_fa();
int m=(n*(n-1))/2,ans=0;
for(int i=0;i<m;i++)
scanf("%d%d%d",&eg[i].x,&eg[i].y,&eg[i].w);
sort(eg,eg+m,cmp);
for(int i=0;i<m;i++)
{
if(find(eg[i].x)!=find(eg[i].y))
{
Union(eg[i].x,eg[i].y);
ans+=eg[i].w;
}
}
printf("%d\n",ans);
}
}
hdu 1233 还是畅通project (克鲁斯卡尔裸题)
原文:http://www.cnblogs.com/gavanwanggw/p/6977917.html