Week6 HomeWork D 数据中心 CSP201812-4 生成树

题目描述

img

Sample Input

4
5
1
1 2 3
1 3 4
1 4 5
2 3 8
3 4 2

Sample Output

4

算法/思路分析

题意翻译成图语言就是在图中找一个生成树,使得该树的最大边权相对于其他生成树最小

按照Kruskal算法的思想,我们可以每次选择成本最小的边,若合法,则合并,合并后我们可以记录/更新该生成树的最大边权,最终,我们记录的最大边权即为所有生成树中的最小值。

代码

#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <vector>
#include <cmath> 
using namespace std;
const int maxn = 1e5+10;
#define ll long long
struct edge
{
	int u,v,w;	
	bool operator<(const edge &p)const
	{
		return w < p.w;
	}
}e[maxn];
int par[maxn], rnk[maxn];
int n,m,root;

void init()
{
	for(int i = 0; i <= n; i++)
	{
		par[i] = i;
		rnk[i] = 1;
	} 
}

int find(int x)
{
	return par[x] == x ? x : par[x] = find(par[x]);
}

bool unite(int x,int y)
{
	x = find(x); y = find(y);
	if(x == y) return false;
	if(x < y) swap(x,y);
	par[x] = y; 
	rnk[y] += rnk[x];
	rnk[x] = rnk[y];
	return true;
}

int main()
{
	scanf("%d%d%d",&n,&m,&root);
	for(int i = 0; i < m; i++)
		scanf("%d%d%d",&e[i].u,&e[i].v,&e[i].w);
	sort(e,e+m);
	init();
	int ans = 0;
	int cnt = 0;
	for(int i = 0; i < m; i++)
	{
		int u = e[i].u;
		int v = e[i].v;
		int w = e[i].w;
		if(unite(u,v))
		{
			ans = max(ans,e[i].w);
			if(cnt == n) break;
			cnt++;
		}
	}
	printf("%d",ans);	
	return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值