UVA_10245_ The Closest Pair Problem

本文介绍了一种使用分治法解决二维平面上点集最小距离问题的方法,并通过C++代码实现了该算法。该算法首先将点集分成两部分,递归地找到各自内部的最小距离,然后检查跨越两个子集的最短距离,最终得到点集中任意两点间最小距离。

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

#include<iostream>        
#include<sstream>        
#include<string>        
#include<vector>        
#include<list>        
#include<set>        
#include<map>        
#include<stack>        
#include<queue>        
#include<algorithm>        
#include<cmath>        
#pragma warning(disable:4996)        
using std::cin;
using std::cout;
using std::endl;
using std::stringstream;
using std::string;
using std::vector;
using std::list;
using std::pair;
using std::set;
using std::multiset;
using std::map;
using std::multimap;
using std::stack;
using std::queue;
double divide_conquer(vector<pair<double,double>>point)
{
	if (point.size() == 1)
	{
		return 1000000000;
	}
	else if (point.size() == 2)
	{
		return sqrt(pow(point[0].first - point[1].first, 2) + pow(point[0].second - point[1].second, 2));
	}
	vector<pair<double, double>> point1;
	point1.assign(point.begin(), point.begin()+point.size()/2);
	vector<pair<double, double>> point2;
	point2.assign(point.begin() + point.size() / 2, point.end());
	auto min = std::min(divide_conquer(point1),divide_conquer(point2));
	for (size_t i = 0; i < point.size() / 2; i++)
	{
		for (size_t j = point.size() / 2; j < point.size(); j++)
		{
			min = std::min(min, sqrt(pow(point[i].first-point[j].first,2)+ pow(point[i].second - point[j].second, 2)));
		}
	}
	return min;
}
int main()
{
	//freopen("input.txt", "r", stdin);
	//freopen("output.txt", "w", stdout);
	int n;
	while (scanf("%d",&n)!=EOF&&n)
	{
		vector<pair<double, double>>point(n);
		for (int i = 0; i < n; i++)
		{
			scanf("%lf%lf", &point[i].first,&point[i].second);
		}
		/*std::sort(point.begin(), point.end());
		auto result = divide_conquer(point);*/
		double result = 10000.0;
		for (int i = 0; i < n; i++)
		{
			for (int j = i + 1; j < n; j++)
			{
				result = std::min(result, sqrt(pow(point[i].first - point[j].first, 2) + pow(point[i].second - point[j].second, 2)));
			}
		}
		if (result >= 10000)
		{
			printf("INFINITY\n");
		}
		else
		{
			printf("%.4lf\n", divide_conquer(point));
		}
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值