题目链接:
POJ 1287 Networking
分析:
裸题。
CODE :
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
const int maxn=55;
int n,m,uu,vv,ww,ans;
int pre[maxn];
struct Edge{
int u,v,w;
}edge[maxn*maxn];
int find(int x)
{
return pre[x]==x?x:pre[x]=find(pre[x]);
}
void init()
{
ans=0;
for(int i=0;i<=n;i++)
pre[i]=i;
}
bool cmp(struct Edge a,struct Edge b)
{
return a.w<b.w;
}
int main()
{
#ifdef LOCAL
freopen("in.txt","r",stdin);
//freopen("out.txt","w",stdout);
#endif
while(~scanf("%d",&n)&&n)
{
init();
scanf("%d",&m);
for(int i=0;i<m;i++)
{
scanf("%d%d%d",&uu,&vv,&ww);
edge[i].u=uu;
edge[i].v=vv;
edge[i].w=ww;
}
sort(edge,edge+m,cmp);
for(int i=0;i<m;i++)
{
uu=edge[i].u;
vv=edge[i].v;
ww=edge[i].w;
int fu=find(uu);
int fv=find(vv);
if(fu!=fv)
{
pre[fu]=fv;
ans+=ww;
}
}
printf("%d\n",ans);
}
return 0;
}