分治寻找最近点对

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

#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;
}

 

posted @ 2017-10-26 22:52  Babetterdj  阅读(328)  评论(0编辑  收藏  举报