hdu 1875 畅通工程再续 (最小生成树)

本文探讨了一个基于真实场景的算法问题——如何在百岛湖的多个小岛间建立桥梁,使得任意两岛间都有路径相连,且总成本最小。通过对输入数据的处理和最小生成树算法的应用,文章详细解释了算法的设计与实现过程,以及如何判断是否能够实现全岛畅通。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1875

相信大家都听说一个“百岛湖”的地方吧,百岛湖的居民生活在不同的小岛中,当他们想去其他的小岛时都要通过划小船来实现。现在政府决定大力发展百岛湖,发展首先要解决的问题当然是交通问题,政府决定实现百岛湖的全畅通!经过考察小组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!

 

把int变成了double。处理double时候用%lf,其他的不变

#pragma GCC optimize(2)
#include<stdio.h>
#include<algorithm>
#include<string.h>
#include<math.h>
#include<queue>
using namespace std;
const int maxn = 10005;
const int inf = 0x3f3f3f3f;
typedef long long ll;
struct node
{
	double u, v;
	int id;
}edge[maxn];
struct node1
{
	int id1, id2;
	double w;
}edge1[maxn];
int f[105];
int n, m;
int find(int x)
{
	if (x == f[x])
	{
		return x;
	}
	else
	{
		return f[x] = find(f[x]);
	}
}
void _union(int a, int b)
{
	int x = find(a);
	int y = find(b);
	if (x != y)
	{
		f[x] = y;
	}
	return;
}
bool cmp(node1 &a, node1 &b)
{
	return a.w < b.w;
}
int main()
{
	//freopen("C://input.txt", "r", stdin);
	int t;
	scanf("%d", &t);
	while (t--)
	{
		int n;
		scanf("%d", &n);
		int tot;
		int oi = 0;
		int flag = 1;
		double sum = 0;
		for (int i = 0; i <= n; i++)
		{
			f[i] = i;
		}
		for(int i = 1;i <= n; i++)
		{
			double u, v;
			scanf("%lf%lf", &u, &v);
			edge[i].id = i;
			edge[i].u = u;
			edge[i].v = v;
		}
		tot = 0;
		for (int i = 1; i <= n; i++)
		{
			for (int j = i+1; j <= n; j++)
			{
				if (i != j)
				{
					edge1[tot].id1 = i;
					edge1[tot].id2 = j;
					double op = (edge[j].u - edge[i].u)*(edge[j].u - edge[i].u);
					double po = (edge[j].v - edge[i].v)*(edge[j].v - edge[i].v);
					edge1[tot++].w = sqrt(op + po);
				}
			}
		}
		sort(edge1, edge1 + tot, cmp);
		for (int i = 0; i < tot; i++)
		{
			if (edge1[i].w < 10 || edge1[i].w > 1000)
			{
				continue;
			}
			int x = find(edge1[i].id1);
			int y = find(edge1[i].id2);
			if (x != y)
			{
				f[x] = y;
				oi++;
				sum += edge1[i].w * 100;
			}
		}
		
		if (oi==n-1)
		{
			printf("%.1lf\n", sum);
		}
		else
		{
			printf("oh!\n");
		}
	}
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值