给定平面上N个点的坐标,要求找出距离最近的两个点
思路:分治法
将平面分为两部分,则距离最近的两个点可能出现的位置为左边、右边或中间两点
因此,分别求出其左右两部分中距离最小的点,最后和中间两点的距离比较,返回最小值即可
code:
// sadfsadf.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
#include <math.h>
using namespace std;
class Point
{
public:
Point(int a = 0 , int b = 0):x(a),y(b){}
double GetDistance(Point p2)
{
double Lx = pow(p2.x - x , 2.0);
double Ly = pow(p2.y - y , 2.0);
double temp = sqrt(Lx+Ly);
return sqrt(temp);
}
void GetPos()
{
cout<<"X:"<<x<<endl;
cout<<"Y:"<<y<<endl;
}
void SetPos(int a,int b)
{x = a , y = b;}
private:
int x;
int y;
};
Point arrPoint[5];
double MinOfThree(double x,double y,double z)
{
if(x <= y && x <= z)
return x;
if(y <= z && y <= x)
return y;
if(z <= x && z <= y)
return z;
}
int times = 0;
double GetMinDistance(Point *arr,int begin,int end)
{
++times;
if(end - begin == 1)
return arr[begin].GetDistance(arr[end]);
int mid = (end - begin) / 2;
if(begin == mid)
++mid;
double MidDistance = arr[mid].GetDistance(arr[mid+1]);
double left = GetMinDistance(arr,begin,mid);
double right = GetMinDistance(arr,mid,end);
cout<<"MidDistance:"<<MidDistance<<endl;
cout<<"left:"<<left<<endl;
cout<<"right:"<<right<<endl;
double temp = MinOfThree(MidDistance,left,right);
cout<<"temp:"<<temp<<endl;
return temp;
}
int _tmain(int argc, _TCHAR* argv[])
{
for(int i = 0 ; i < 5 ; ++i)
arrPoint[i].SetPos(i*i,i+1);
cout<<GetMinDistance(arrPoint,0,3)<<endl;;
cout<<"times:"<<times<<endl;
return 0;
}