HDU1007 求最短距离的点对

#include<iostream>
#include<cmath>
#include<algorithm>
#include<iomanip>
using namespace std;
struct sys
{
	double x;
	double y;
};

sys num[100001],num1[100001],num2[100001];

bool cmpy(sys dot1,sys dot2)
{
	if(dot1.y==dot2.y) return dot1.x<dot2.x;
	return dot1.y<dot2.y;
}

bool cmpx(sys dot1,sys dot2)
{
	if(dot1.x==dot2.x) return dot1.y<dot2.y;
	return dot1.x<dot2.x;
}

double getmin(double a,double b,double c)
{
	double minx=min(a,b);
	if(minx>c) minx=c;
	return minx;
}
double getdistancex(sys dot1,sys dot2)
{
	double m=sqrt((dot1.x-dot2.x)*(dot1.x-dot2.x)+(dot1.y-dot2.y)*(dot1.y-dot2.y));
	return m;
}
double getdistancey(int low,int high)
{
	int count = high -low;
	double dis=0;
	if(count==0)  return 0;
	else if(count==1) {
		dis=getdistancex(num[low],num[high]);
		return dis;
	}
	else if(count==2)
	{
		double tem1= getdistancex(num[low],num[low+1]);
		double tem2= getdistancex(num[low+1],num[high]);
		double tem3= getdistancex(num[low],num[high]);
		dis=getmin(tem1,tem2,tem3); 
		return dis;
	}
	else 
	{
		double leftmin,rightmin;
		int mid=(high + low)/2;
		
		leftmin=getdistancey(low,mid);
		rightmin=getdistancey(mid+1,high);
		dis=min(leftmin,rightmin);
		
		int p=0;
		for(int i=low;i<=high;i++)
		{
			if(fabs(num[i].x-num[mid].x)<dis)
			num1[p++]=num[i];
		}
		sort(num1,num1+p,cmpy);
		mid=p/2;
		int k=0;
		for(int i=0;i<p;i++)
		{
			if(fabs(num1[i].y-num1[mid].y)<dis)
			num2[k++]=num1[i];
		}
		for(int i=0;i<k;i++)
		{
			for(int j=i+1;j<k;j++)
			{
				if(getdistancex(num2[i],num2[j])<dis)
				dis=getdistancex(num2[i],num2[j]);
				
			}
		}
		return dis;
	}
}
int main()
{
	int n;
	while(cin>>n&&n!=0)
	{
		for(int i=0;i<n;i++)
		{
			cin>>num[i].x>>num[i].y;
		}
		sort(num,num+n,cmpx);
		double min=getdistancey(0,n-1);
		cout<<fixed<<setprecision(2)<<min/2<<endl;
	}
	return 0;
}

你可能感兴趣的:(HDU1007 求最短距离的点对)