返回

poj1287 Networking【最小生成树】

发布时间:2022-12-04 12:12:41 290

题目链接:​​http://poj.org/problem?id=1287​​​
题意:类似n个点,m条边,每条边需要花费一定的代价才能联通,问你把n个点联通的最小花费
解析:最小生成树裸题

#include 
#include
#include
#include
using namespace std;
const int maxn = 1e5+100;
struct node
{
int x,y,v;
bool operator < (const node &b)const
{
return v<b.v;
}
}a[maxn];
int fa[maxn];
void init(int n)
{
for(int i=0;i<=n;i++)
fa[i] = i;
}
int getfa(int x)
{
if(x==fa[x])
return x;
return fa[x] = getfa(fa[x]);
}
int main(void)
{
int n,m;
while(~scanf("%d",&n)&&n)
{
scanf("%d",&m);
init(n);
for(int i=0;i<m;i++)
scanf("%d %d %d",&a[i].x,&a[i].y,&a[i].v);
sort(a,a+m);
int ans = 0;
for(int i=0;i<m;i++)
{
int t1 = getfa(a[i].x);
int t2 = getfa(a[i].y);
if(t1!=t2)
{
fa[t1] = t2;
ans += a[i].v;
}
}
printf("%d\n",ans);
}
return 0;
}

 

特别声明:以上内容(图片及文字)均为互联网收集或者用户上传发布,本站仅提供信息存储服务!如有侵权或有涉及法律问题请联系我们。
举报
评论区(0)
按点赞数排序
用户头像
精选文章
thumb 中国研究员首次曝光美国国安局顶级后门—“方程式组织”
thumb 俄乌线上战争,网络攻击弥漫着数字硝烟
thumb 从网络安全角度了解俄罗斯入侵乌克兰的相关事件时间线
下一篇
hdu6109 数据分割【并查集+set】 2022-12-04 11:48:02