分治寻找最近点对

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了分治寻找最近点对相关的知识,希望对你有一定的参考价值。

***改天增加下算法总结

#include <iostream>
#include <cstdio>
#include <cmath>  
#include <algorithm>
#include <vector>

#define n 100000

using namespace std;


struct point{
	double x;
	double y;
};

point p[n], temp[n];

inline double pDistance(point &a,point &b)//相当于宏函数 
{
	return sqrt((a.x - b.x)*(a.x - b.x) + (a.y - b.y)*(a.y - b.y));
}

inline double min(double a , double b)  
{  
    return a < b ? a : b;  
}  

bool xCmp(point &a,point &b)//因为是个struct所以要规定什么是小于 
{
	return a.x < b.x;
}

bool yCmp(point &a,point &b)
{
	return a.y < b.y;
}

double minDistance(int b,int e)//stands for begin and end
{
	int mid = (b + e)/2,count = 0,i = 0,j = 0;
	double ans = 0;
	if(b == e)
		return 1.79769e+308;//the max double stands for wrong
	else if(e == b + 1)
		return pDistance(p[b],p[e]);


	ans=min(minDistance(b,mid),minDistance(mid+1,e));//find the d in two half parts

	for(i = mid;i >= b&&p[mid].x - p[i].x < ans;i--)//put point we need in temp
	{
		temp[count++] = p[i];
	}

	for(i = mid + 1;i <= e&&p[mid].x - p[i].x < ans;i++)
	{
		temp[count++] = p[i];
	}

	sort(temp,temp + count,yCmp);//sorted by y
    
    for(i = 0 ; i < count; ++i)  
    {  
        for(j = i + 1 ; j < count ; ++j)  
        {  
            ans = min(ans , pDistance(temp[i] , temp[j]));  
        }  
    }
	return ans;
}

int main()
{
	int pNumber,i;
	char see;
	cout<<"Please input the number of point you want(at most 10000):";
	cin>>pNumber;
	
	vector<int> temp;//生成100以内随机小数并填充 
	for (i = 0; i < n; ++i)
	{
		temp.push_back(i + 1);
	} 
    random_shuffle(temp.begin(), temp.end());
    for (i = 0; i < temp.size(); i ++)
    {
    	p[i].x =  temp[i]/1000.0;
    }
    random_shuffle(temp.begin(), temp.end());
    for (i = 0; i < temp.size(); i ++)
    {
    	p[i].y =  temp[i]/1000.0;
    }
    cout<<"Do you want to see the points?(Y/N)";
	cin>>see;
	if(‘y‘ == see || ‘Y‘ == see)
	{
		for(i = 0;i < pNumber;i ++)
		{
			cout<<p[i].x<<" "<<p[i].y<<endl;
		}
	}
	cout<<"Points are generated!"<<endl<<"Start to caculate!"<<endl;//提示填充完毕 
	
	sort(p,p + pNumber,xCmp);//
	cout<<endl<<"The minimum distance of the points is:"<<minDistance(0 ,pNumber - 1)<<endl;
	
	return 0;
}

 

以上是关于分治寻找最近点对的主要内容,如果未能解决你的问题,请参考以下文章

平面最近点对(分治nlogn)

分治——最近点对

POJ 3714 分治/求平面最近点对

poj3714 Raid(分治求平面最近点对)

分治&暴力求解最近点对问题 + 时间性能量化分析

分治法二(平面最近点对)