如果存在多个最近点对,则查找所有最近的点对
finding all closest point pairs if multiple closest pairs exist
以下代码用于查找C++梁教科书编程导论中的最接近点对问题。 我正在尝试编辑它,以便如果存在多个最接近的点对,它可以找到所有最近的点对。
#include <iostream>
#include <cmath>
using namespace std;
/** Compute the distance between two points (x1, y1) and (x2, y2) */
double getDistance(double x1, double y1, double x2, double y2)
{
return sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));
}
int main()
{
const int NUMBER_OF_POINTS = 8;
// Each row in points represents a point
double points[NUMBER_OF_POINTS][2];
cout << "Enter " << NUMBER_OF_POINTS << " points: ";
for (int i = 0; i < NUMBER_OF_POINTS; i++)
cin >> points[i][0] >> points[i][1];
// p1 and p2 are the indices in the points array
int p1 = 0, p2 = 1; // Initial two points
double shortestDistance = getDistance(points[p1][0], points[p1][1],
points[p2][0], points[p2][1]); // Initialize
// Compute distance for every two points
for (int i = 0; i < NUMBER_OF_POINTS; i++)
{
for (int j = i + 1; j < NUMBER_OF_POINTS; j++)
{
double distance = getDistance(points[i][0], points[i][1],
points[j][0], points[j][1]); // Find distance
if (shortestDistance > distance)
{
p1 = i; // Update p1
p2 = j; // Update p2
shortestDistance = distance; // Update shortestDistance
}
}
}
// Display result
cout << "The closest two points are " <<
"(" << points[p1][0] << ", " << points[p1][1] << ") and (" <<
points[p2][0] << ", " << points[p2][1] << ")";
return 0;
}
我通过使用一个新的数组解决了它,距离点,并在计算距离时用点对保存距离,之后我循环新数组并打印出最短的距离,但我认为肯定有更智能的解决方案,我在编程方面很新:)
double distance_points[28][5];
int f = 0 ;
// Compute distance for every two points
for (int i = 0; i < NUMBER_OF_POINTS; i++)
{
for (int j = i + 1; j < NUMBER_OF_POINTS; j++)
{
double distance = getDistance(points[i][0], points[i][1],
points[j][0], points[j][1]); // Find distance
distance_points[f][0] = distance;
distance_points[f][1] = points[i][0];
distance_points[f][2] = points[i][1];
distance_points[f][3] = points[j][0];
distance_points[f][4] = points[j][1];
f++;
}
}
您可以更改算法以在向量中存储结果:
std::vector<int> p1, p2;
double shortestDistance = getDistance(points[p1][0], points[p1][1],
points[p2][0], points[p2][1]); // Initialize
for (int i = 0; i < NUMBER_OF_POINTS; i++) {
for (int j = i + 1; j < NUMBER_OF_POINTS; j++) {
const double distance = getDistance(points[i][0], points[i][1],
points[j][0], points[j][1]);
if (shortestDistance >= distance) {
if (shortestDistance > distance) {
p1.clear();
p2.clear();
shortestDistance = distance; // Update shortestDistance
}
p1.push_back(i); // Update p1
p2.push_back(j); // Update p2
}
}
}
相关文章:
- 正在查找文档以获得PS4平台的C++中的设备信息
- 在C++中查找文件
- 模板元程序查找相似的连续类型名称
- 在UNIX系统中使用DIR查找文件的字节大小
- 查找最近配对时的OpenMP竞赛条件
- 在 3D 点云、GPU 中查找最近的邻居
- 我最近正在阅读opencv源代码。有没有更好的方法来在opencv库中查找类定义?
- 在 OpenCV 和 C++ 中查找距轮廓中心最近的黑色像素
- 查找与当前时间最近的时间
- C++-使用opencv-frann查找最近的邻居
- 从点向量中查找最近的点
- 如果存在多个最近点对,则查找所有最近的点对
- 具有最近路径前缀回退的查找树
- 在 KD 树中查找最近的邻居
- 查找最近的邻居-OpenCV
- 查找最近的较小素数的快速算法
- 查找最近的点对-如何在递归侧对函数调用中实现拆分对
- 查找网格上离查询点最近的点
- 查找集合中最近的元素
- 在std::map中查找输入数字的最近范围的最有效的std算法是什么?