Acwing_1145北极通讯网络【最小生成树扩展应用】

思路分析:
题目要求的其实就是最小生成树后,取第K大的边,因为要求所有的点连通,并且可以选择其中k个点的权值变为0,求其中最小生成树的最大边最小。

AC代码:

//找一个最小d值,使得将所有权值大于d的边删除之后,整个图形的连通块的个数不超过k

#include <cstring>
#include <iostream>
#include <algorithm>
#include <cmath>

#define x first
#define y second

using namespace std;

typedef pair<int, int> PII;

const int N = 510, M = N * N / 2;

int n, k, m;
struct Edge
{
	int a, b;
	double w;
	bool operator< (const Edge &t) const
	{
		return w < t.w;
	}
}e[M];
PII q[M];
int p[N];

double get_dist(PII a, PII b)
{
	int dx = a.x - b.x;
	int dy = a.y - b.y;
	return sqrt(dx * dx + dy * dy);
}

int find(int x)
{
	if (p[x] != x) p[x] = find(p[x]);
	return p[x];
}

int main()
{
	cin >> n >> k;
	for (int i = 0; i < n; i++) cin >> q[i].x >> q[i].y;
	for (int i = 0; i < n; i++)
		for (int j = 0; j < i; j++)
			e[m++] = { i, j, get_dist(q[i], q[j]) };

	sort(e, e + m);
	for (int i = 0; i < n; i++) p[i] = i;

	int cnt = n;
	double res = 0;
	for (int i = 0; i < m; i++)
	{
		if (cnt <= k) break;

		int a = find(e[i].a), b = find(e[i].b);
		double w = e[i].w;
		if (a != b)
		{
			p[a] = b;
			cnt--;
			res = w;
		}
	}

	printf("%.2lf\n", res);

	return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值