最近对问题
1、问题
求二维平面两点之间的最短距离。(最近对问题)。
2、解析
Struct node对点结构进行定义,结构数组进行保存。解法一(蛮力法):对每两个点之间进行距离计算,筛选出距离最近的两个点。解法二(分治法):进行对很坐标x排序将所有点分为左右两部分,不断进行递归求得最短距离递归出口当只有两个或者三个点在子集合里需要特别注意的是,在center-d,center+d范围内有可能距离小于最短距离d,对纵坐标y排序,排除特殊情况。
3、设计
struct node
{
Int x,y;
};
bool cmp1(node p1,node p2)
{
Return p1.x<p2.y;
}
bool cmp2{
return p1.y<p2.y;
}
double distance(node p1,node p2)
{
return sqrt((p1.x-p2.x)(p1.x-p2.x)+(p1.y-p2.y)(p1.y-p2.y));
}
double find(node p[],int left,int right)
{
if(right-left1)…
Else if(right-left2)…
else{int center=(right+left)/2;
double d1=fin1(p,left,center);
double d2=find(p,center+1,right);
double d=min(d1,d2)
Int low=left,right=high;
while (p[low].x < p[center].x - d && low <=right) {
low++;
}
while (p[high].x> p[center].x +d && high>=left) {
high–;
}
double d3;
sort(p +low, p + high + 1, cmp2);
for (int i = low; i < high; i++) {
for (int j = i + 1; j < high; j++) {
d3 = distance(p[i],p[j]);
if (d3 <d) {
d = d3;
}
}
}
return d;
}
}
}
4、分析
蛮力法:O(n²)
分治法(nlogn)
5、源码
源码地址:https://github.com/ACynj/manli.git
https://github.com/ACynj/fenzhi.git