zoj2107 平面最近点对

先按照x排序,然后分治,先求出左边一半的最小值,再求出右边一半的最小值。

最后只要考虑跨过中间mid 的 点对是否为最小距离就行了

假设当前最短距离时ans,我们找到x坐标在(a[mid].x-ans,a[mid].x+ans)之间的点,然后对他们按照y坐标排序,

对于每一个点,只要找离它y坐标最近的5个点更新最短距离就行了,可以画图理解为啥是5个

但是书上写的是6个,也有博客说7个。。。我感觉是5个就够了

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#define maxl 100010
#define eps 1e-8
using namespace std;

inline int sgn(double x)
{
	if(x>-eps && x<eps) return 0;
	if(x>0) return 1;
	else	return -1;
}

struct point
{
	double x,y;
	point(double a=0,double b=0)
	{
		x=a;y=b;
	}
	point operator + (const point &b)const
	{
		return point(x+b.x,y+b.y);
	}
	point operator - (const point &b)const
	{
		return point(x-b.x,y-b.y);
	}
	inline double norm()
	{
		return sqrt(x*x+y*y);
	}
};
inline double dot(const point &a,const point &b)
{
	return a.x*b.x+a.y*b.y;	
}
inline double det(const point &a,const point &b)
{
	return a.x*b.y-a.y*b.x;
}

int n;
int s[maxl];
point a[maxl];
double ans;

inline bool cmpx(const int &x,const int &y)
{
	return sgn(a[x].x-a[y].x)<0;
}
inline bool cmpy(const int &x,const int &y)
{
	return sgn(a[x].y-a[y].y)<0;
}

inline void prework()
{
	for(int i=0;i<n;i++)
		scanf("%lf%lf",&a[i].x,&a[i].y),s[i]=i;
	sort(s,s+n,cmpx);
}

double min_dist(point a[],int s[],int l,int r)
{
	double ans=1e100;
	if(r-l<20)
	{
		for(int i=l;i<r;i++)
			for(int j=i+1;j<r;j++)
				ans=min(ans,(a[s[i]]-a[s[j]]).norm());
		return ans;
	}
	int tl,tr,m=(l+r)>>1;
	ans=min(min_dist(a,s,l,m),min_dist(a,s,m,r));
	tl=l;tr=r-1;
	while(a[s[tl]].x<a[s[m]].x-ans)
		tl++;
	while(a[s[tr]].x>a[s[m]].x+ans)
		tr--;
	sort(s+tl,s+tr,cmpy);
	for(int i=tl;i<tr;i++)
		for(int j=i+1;j<min(tr,i+6);j++)
			ans=min(ans,(a[s[i]]-a[s[j]]).norm());
	sort(s+tl,s+tr,cmpx);
	return ans;
}

inline void mainwork()
{
	ans=min_dist(a,s,0,n);
}

inline void print()
{
	printf("%.2f\n",ans/2);
}

int main()
{
	while(~scanf("%d",&n) && n)
	{
		prework();
		mainwork();
		print();
	}	
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值