平面最小距离对问题 分治算法

详细的讲解戳这儿 https://blog.csdn.net/qq_40707370/article/details/85268256?tdsourcetag=s_pcqq_aiomsg

#include<bits/stdc++.h>
using namespace std;

const int INF = 0x3fffffff;

int n;

struct Point
{
	double x,y;
	Point(double x=0, double y=0):x(x),y(y) {}
	bool operator < (const Point& p) const
	{
		if(x != p.x)	return x < p.x;
		else	return y < p.y;
	}
}p[200000+5],temp[200000+5];

bool cmpy(Point a, Point b)
{
	return a.y < b.y;
}

double Dis(Point a, Point b)
{
	return sqrt((a.x-b.x)*(a.x-b.x) + (a.y-b.y)*(a.y-b.y));
}

double Closest_Pair(int left, int right)
{
	double d = INF;
	if(left == right)
		return d;
	if(left +1 == right)
		return Dis(p[left],p[right]);
	int mid = (left+right)>>1;
	double d1 = Closest_Pair(left,mid);
	double d2 = Closest_Pair(mid,right);
	d = min(d1,d2);
	int k = 0;
	for(int i = left; i <= right; i++)
	{
		if(fabs(p[mid].x - p[i].x) <= d)
			temp[k++] = p[i];
	}
	sort(temp,temp+k,cmpy);
	for(int i = 0; i < k; i++)
	{
		for(int j = i+1; j < k && temp[j].y - temp[i].y < d; j++)
		{
			double d3 = Dis(temp[i],temp[j]);
			d = min(d,d3);
		}
	}
	return d;
}


int main()
{
	cin>>n;
	for(int i=0; i<n; i++)
	{
		double a,b;
		scanf("%lf%lf",&a,&b);
		p[i] = Point(a,b);
	}
	sort(p,p+n);
	printf("%.2f",Closest_Pair(0,n-1));
}

 

另外此问题还有一种扫描线算法 

https://blog.csdn.net/LiRewriter/article/details/77512370?tdsourcetag=s_pcqq_aiomsg

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值