一维最接近点对(递归分治)

来源:互联网 发布:大数据推荐系统 视频 编辑:程序博客网 时间:2024/05/21 09:10
//一维情况下的最接近点对#include<iostream>using namespace std;#include<stdio.h>#include<math.h>#include<time.h>#include<stdlib.h>#define maxint 1000template<class Type>void Swap(Type &a,Type &b){Type temp = a;a = b;b = temp;}/*template<class Type>Type min(Type a,Type b,Type c){Type temp = a > b ? b:a;return temp < c ? temp:c;}*/template<class Type>int Partition(Type a[],int p,int r){int i = p,j = r+1;Type x = a[p];while(true){while(a[++i] < x && i < r);while(a[--j] > x);if(i >= j)break;Swap(a[i],a[j]);}a[p] = a[j];a[j] = x;return j;}template<class Type>int RandomizedPartition(Type a[],int p,int r){int i = p + rand()%(r-p);Swap(a[i],a[p]);return Partition(a,p,r);}template<class Type>void RandomizedQuickSort(Type a[],int p,int r){if(p < r){int q = RandomizedPartition(a,p,r);RandomizedQuickSort(a,p,q-1);RandomizedQuickSort(a,q+1,r);}}template<class Type>Type RandomizedSelect(Type a[],int p,int r){//返回中位数if(p == r)return a[p];else return a[(p+r)/2];}/*template<class Type>Type Cpair1(Type a[],int n){//只是输出最小距离版本的Type dmin = maxint;//表示最接近点对的距离//a为一位数组,表示x轴上的点,n为点的数目if(n < 2){d = maxint;return d;}Type d1 = Cpair1(a,(n+1)/2);//递归求解Type d2 = Cpair1(&a[(n+1)/2],n/2);//递归求解Type p = a[(n+1)/2 - 1];//左侧最大的点Type q = a[(n+1)/2];//右侧最小的点d = min(d1,d2,q-p);return d;}*/template<class Type>Type Cpair1(Type a[],int n,Type &pleft,Type &qright){Type d = maxint;//表示最终最接近点对的距离//a为一位数组,表示x轴上的点,n为点的数目if(n < 2){d = maxint;return d;}int d1_p,d1_q;int d2_p,d2_q;Type d1 = Cpair1(a,(n+1)/2,d1_p,d1_q);//递归求解Type d2 = Cpair1(&a[(n+1)/2],n/2,d2_p,d2_q);//递归求解Type p = a[(n+1)/2 - 1];//左侧最大的点Type q = a[(n+1)/2];//右侧最小的点if ( d1 < d2 ) {if( d1 < (q-p) ){pleft = d1_p;qright = d1_q;d = d1;}else{ // q-p is smallest, p ,q no changespleft = p;qright = q;d = q-p;}}else{  // d2 >= d1if( d2 < (q-p) ){pleft = d2_p;qright = d2_q;d = d2;}else{ // q-p最小pleft = p;qright = q;d = q-p;}}return d;}void main(){int a[5] = {3,6,8,10,14};int pleft = maxint,qright = maxint;RandomizedQuickSort(a,0,4);cout<<"x轴上点的中位点是:"<<"("<<RandomizedSelect(a,0,4)<<",0)";cout<<endl<<"最接近的两点的距离是:"<<Cpair1(a,5,pleft,qright)<<endl;cout<<endl<<"两个点为"<<"("<<pleft<<",0)"<<" , ("<<qright<<",0)"<<endl;}