ACM - 畅通工程再续

畅通工程再续

相信大家都听说一个“百岛湖”的地方吧,百岛湖的居民生活在不同的小岛中,当他们想去其他的小岛时都要通过划小船来实现。现在政府决定大力发展百岛湖,发展首先要解决的问题当然是交通问题,政府决定实现百岛湖的全畅通!经过考察小组RPRush对百岛湖的情况充分了解后,决定在符合条件的小岛间建上桥,所谓符合条件,就是2个小岛之间的距离不能小于10米,也不能大于1000米。当然,为了节省资金,只要求实现任意2个小岛之间有路通即可。其中桥的价格为 100元/米。

Input
输入包括多组数据。输入首先包括一个整数T(T <= 200),代表有T组数据。
每组数据首先是一个整数C(C <= 100),代表小岛的个数,接下来是C组坐标,代表每个小岛的坐标,这些坐标都是 0 <= x, y <= 1000的整数。

Output
每组输入数据输出一行,代表建桥的最小花费,结果保留一位小数。如果无法实现工程以达到全部畅通,输出”oh!”.

Sample Input
2
2
10 10
20 20
3
1 1
2 2
1000 1000

Sample Output
1414.2
oh!

最小生成树:
Kruskal算法(贪心算法在图论生成树中的应用)
要求边的权值和最小,我就按权值从小到大的边开始取,如果这条边的添加不不会形成圈(环),就取这条边。(因为形成环,相当于做了无用功,本来这个联通块里的顶点就相互可达)。满足这样的条件取n-1条边就可以了。
判是否形成环的时候使用并查集,如果这条边连的两条边在同一个集合里,添加这条边就会形成环。

#include <cstring>
#include <cmath>
#include <algorithm>
#include <iostream>
#include <string>
#include <queue>
#include <deque>
#include <stack>
#include <map>
#include <set>
#include <vector>
#define INF  0x3f3f3f3f
#define mod 998244353
#define PI acos(-1)
using namespace std;
typedef long long ll;
int node[105][2];
int c;
int fa[105];
inline int find(int x)
{
	int r = x, q;
	while (fa[r] != r)
		r = fa[r];
	while (r != x)
	{
		q = fa[x];
		fa[x] = fa[q];
		x = q;
	}
	return r;
}
inline void unit(int x, int y)
{
	x = find(x);
	y = find(y);
	fa[y] = x;
}
struct Edge {
	int from, to;
	double value;
	bool operator < (const Edge& rhs) const
	{
		return value < rhs.value;
	}
};
bool Kruskal(Edge* es, int m, double& ret)
{
	int cn = 0;
	for (int i = 0; i < 105; i++)
		fa[i] = i;
	ret = 0; // 生成权置为0
	sort(es, es + m); // 按边权排序
	for (int i = 0; i < m; i++)
	{
		int f = es[i].from, t = es[i].to;
		// 添加这条边形成环或点间距离小于10,大于1000跳过
		if (find(f) == find(t) || es[i].value < 10 || es[i].value > 1000) 
			continue;
		ret += es[i].value;
		unit(f, t); 
		cn++;
	}
	if (cn == c - 1) return true;
	else return false;
}
Edge esn[10005];
int main()
{
	int k;
	cin >> k;
	while (k--)
	{
		int x, y, cnt = 0;
		cin >> c;// 小岛个数
		for (int i = 1; i <= c; i++)
		{
			cin >> x >> y;
			node[i][0] = x;
			node[i][1] = y;
			for (int j = 1; j < i ; j++)
			{
				esn[cnt].from = i;
				esn[cnt].to = j;
				esn[cnt].value = sqrt((x - node[j][0]) * (x - node[j][0]) + 
									 (y - node[j][1]) * (y - node[j][1]));
				cnt++;
			}
		}
		double ret = 0;
		if (Kruskal(esn, cnt, ret))
			printf("%.1f\n", ret * 100);
		else printf("oh!\n");
		memset(node, 0, sizeof(node));
		memset(esn, 0, sizeof(esn));
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值