最近点对问题c++代码
时间: 2023-10-26 22:05:46 浏览: 109
最近点对问题是一个经典的计算几何问题,可以用于寻找平面上最近的两个点。以下是一个使用C语言实现的简单代码示例:
```c
#include <stdio.h>
#include <math.h>
struct Point {
int x, y;
};
float distance(struct Point p1, struct Point p2) {
return sqrt(pow(p2.x - p1.x, 2) + pow(p2.y - p1.y, 2));
}
float closestPair(struct Point points[], int n) {
float minDist = INFINITY;
for (int i = 0; i < n; i++) {
for (int j = i+1; j < n; j++) {
float dist = distance(points[i], points[j]);
if (dist < minDist) {
minDist = dist;
}
}
}
return minDist;
}
int main() {
struct Point points[] = {{0, 0}, {1, 1}, {2, 2}, {3, 3}};
int n = sizeof(points) / sizeof(points[0]);
float closestDist = closestPair(points, n);
printf("The closest pair distance is: %f\n", closestDist);
return 0;
}
```
阅读全文