编程之美2.11-寻找最近点对

给定平面上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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值