HDU - 1233 还是畅通工程

https://vjudge.net/problem/HDU-1233

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
const int N=110,M=N*N/2;
int n,m;
int p[N];
struct node{
	int u,v,w;
	bool operator< (const node W)const
	{
		return w<W.w;
	}
}g[M];
int find(int x)
{
	if(p[x]!=x) p[x]=find(p[x]);
	return p[x];
}
int kruskal()
{
	sort(g,g+m);
	for(int i=1;i<=n;i++) p[i]=i;
	int ans=0,cnt=0;
	for(int i=0;i<m;i++)
	{
		int a=find(g[i].u),b=find(g[i].v);
		if(a!=b)
		{
			p[a]=b;
			ans+=g[i].w;
			cnt++;
		}
		if(cnt==n-1) break;
	}
	return ans;
}
int main()
{
	while(~scanf("%d",&n))
	{
		if(n==0) break;
		m=n*(n-1)/2;
		for(int i=0;i<m;i++)
			scanf("%d %d %d",&g[i].u,&g[i].v,&g[i].w);
			
		printf("%d\n",kruskal());
	}
	return 0;
}
posted @ 2021-07-28 18:46  斯文~  阅读(7)  评论(0)    收藏  举报

你好!