平面最近点距离问题(分治法) C++

#include <stdio.h>
#include <iostream>
#include <climits>
#include <algorithm>
using namespace std;
const int maxn = 100010;
struct point
{
	double x;
	double y;
};
int n;
point P[maxn];
int temp[maxn];

double calDis(int a, int b)
{
	double dis = sqrt((P[a].x - P[b].x) * (P[a].x - P[b].x)*1.0 + 
		(P[a].y - P[b].y) * (P[a].y - P[b].y))*1.0;
	return dis;
}

bool cmpxy(const point& a, const point& b)
{
	if (a.x != b.x)
		return a.x < b.x;
	return a.y < b.y;
}

bool cmpy(int a, int b)
{
	return P[a].y < P[b].y;
}

double minDis(int left, int right)
{
	if (left == right)
	{
		return INT_MAX;
	}
	else if (left + 1 == right)
	{
		return calDis(left, right);
	}
	else {
		int mid = (left+right)>>1;
		double d1 = minDis(left, mid);
		double d2 = minDis(mid + 1, right);
		double d = min(d1, d2);
		int k = 0;
		//先找到距离重点d的点
		for (int i = left; i <= right; i++)
		{
			if (abs(P[i].x - P[mid].x) <= d)
			{
				temp[k++] = i;
			}
		}
		sort(temp, temp + k, cmpy);
		for (int i = 0; i < k; i++)
		{
			for (int j = i + 1; j < k && (P[temp[i]].y-P[temp[j]].y) < d; j++)
			{
				double d3 = calDis(temp[i],temp[j]);
				if (d > d3)
					d = d3;
			}
		}
		return d;
	}
	
}

int main()
{
	cin >> n;
	for (int i = 0; i < n; i++)
	{
		cin >> P[i].x >> P[i].y;
	}
	sort(P, P + n, cmpxy);
	double ans = minDis(0, n - 1);
	if (ans > 10000)
	{
		cout << "INFINITY";
	}
	else {
		printf("%.4lf", ans);
	}
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值