最近对问题---蛮力法,分治法实现
问题描述:
在包含n个端的集合中找到距离最近的两个点.
解决方案:
1. 蛮力法:
- 解题思路:
使用结构体数组保存每个坐标。
通过双重for循环遍历所有坐标之间的距离,找到其中距离最小的两个点将其输出。
(距离应该为sqrt((x1-x2)^2 + (y1-y2)^2),但是为了方便我们可以直接比较(x1-x2) ^2+ (y1-y2)^2)的大小就行了。)
代码演示:
//最近对:蛮力法
#include <iostream>
#include <cstdio>
using namespace std;
struct Node{
int x;
int y;
};
int main()
{
Node node[20];
cout << "请输入点的个数:";
int n;
cin >> n;
cout << "请输入点的坐标:"<<endl;
for(int i=0;i<n;i++)
{
cin >> node[i].x >> node[i].y;
}
//假设node[0],node[1]最短并标记。
int min = (node[0].x - node[1].x)*(node[0].x - node[1].x) + (node[0].y - node[1].y)*(node[0].y - node[1].y);
Node node1,node2;
node1=node[0];
node2=node[1];
for(int i=0;i<n;i++)
{
for(int j=i+1;j<n;j++)
{
//标记最短距离所对应的坐标。
int temp = (node[i].x-node[j].x)*(node[i].x-node[j].x)+(node[i].y-node[j].y)*(node[i].y-node[j].y);
if(min > temp)
{
node1=node[i];
node2=node[j];
}
}
}
cout << "最近对为:" << endl;
printf("(%d,%d)和(%d,%d)\n",node1.x,node1.y,node2.x,node2.y);
return 0;
}
2. 分治法:
- 解题思路:
使用含x,y的结构体数组p[n]来存储每个坐标。 - 分解:
对所有的点按照x坐标从小到大排序。
根据下标进行分割,使得点集分为两个集合。 - 解决:
递归的寻找两个集合中的最近点对。
取两个集合最近点对d1,d2中的最小值d=min(d1,d2); - 合并
最近距离不一定存在于两个集合中,可能一个点在集合SL,一个点在集合SR,而这两点间距离小于d。
然后计算出中间这些坐标中的最小距离d3与d相比较,d=min(d,d3);
//最近对:分治法
#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
using namespace std;
struct node{
int x;
int y;
};
bool compare1(node p1,node p2)
{
return p1.x < p2.x;
}
bool compare2(node p1,node p2)
{
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 partition(node p[],int left,int right)
{
//如果只有两个或者3个就直接算出距离返回
if(right - left == 1)
{
return distance(p[left],p[right]);
}
if(right - left == 2)
{
double d1 = distance(p[left],p[left+1]);
double d2 = distance(p[left],p[right]);
double d3 = distance(p[left+1],p[right]);
d2 = min(d1,d2);
d3 = min(d2,d3);
return d3;
}
//当坐标多于两个的时候,将其分成两部分,依次运算。
int m = (left + right)/2;
double d1 = partition(p,left,m);
double d2 = partition(p,m+1,right);
double d = min(d1,d2);
int l=left,r=right;
//筛选中间可能距离最小的坐标。排除x之差大于d的坐标。
while(p[l].x<p[m].x-d && l<=right)
{
l++;
}
while(p[r].x>p[m].x+d && l<=left)
{
r--;
}
double d3;
//将筛选后的坐标以y的大小进行排序。
sort(p+l,p+r+1,compare2);
for(int i=l;i<r;i++)
{
for(int j=i+1;j<r;j++)
{
//筛选中间可能距离最小的坐标。排除y之差大于d的坐标。
if(p[j].y-p[i].y > d)
{
break;
}
else
{
d3 = distance(p[i],p[j]);
if(d3 < d)
{
d = d3;
}
}
}
}
}
int main()
{
node p[20];
cout << "请输入点数:";
int n;
cin >> n;
cout << "请输入坐标:" << endl;
for(int i=0;i<n;i++)
{
cin >> p[i].x >> p[i].y;
}
//根据每个坐标的x排序。
sort(p,p+n,compare1);
double d = partition(p,1,n);
cout << "最短距离为:" << d << endl;
return 0;
}