一維最接近點對(遞迴分治)

2021-09-30 09:38:27 字數 1275 閱讀 2484

//一維情況下的最接近點對

#includeusing namespace std;

#include#include#include#include#define maxint 1000

templatevoid swap(type &a,type &b)

/*templatetype min(type a,type b,type c)*/

templateint partition(type a,int p,int r)

a[p] = a[j];

a[j] = x;

return j;

}templateint randomizedpartition(type a,int p,int r)

templatevoid randomizedquicksort(type a,int p,int r)

}templatetype randomizedselect(type a,int p,int r)

/*templatetype cpair1(type a,int n)

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;}*/

templatetype cpair1(type a,int n,type &pleft,type &qright)

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 ) else

}elseelse

} return d;

}void main();

int pleft = maxint,qright = maxint;

randomizedquicksort(a,0,4);

cout<

cout<

cout<

}

平面最接近點對問題 分治

主要思想就是分治。先把n個點按x座標排序,然後求左邊n 2個和右邊n 2個的最近距離,最後合併。合併要重點說一下,比較麻煩。首先,假設點是n個,編號為1到n。我們要分治求,則找乙個中間的編號mid,先求出1到mid點的最近距離設為d1,還有mid 1到n的最近距離設為d2。這裡的點需要按x座標的順序...

最接近點對問題

一維最臨近點對 假設我們用x軸上某個點m將s劃分為2個子集s1和s2 基於平衡子問題的思想,用s中各點座標的中位數來作分割點。遞迴地在s1和s2上找出其最接近點對和,並設d min,s中的最接近點對或者是,或者是,或者是某個,其中p3 s1且q3 s2。如果s的最接近點對是,即 p3 q3 由於在s...

最接近的點對問題

一 問題描述 給定平面上n個點,找其中一對點,使得在n個點組成的所有點對中,該點對間的距離最小。二 演算法描述 偽 double cpair point p,int left int right n p.size if n 2 return 0x3f3f3f3f 1 int mid left rig...