设p1=(x1,y1),p2=(x2,y2)...pn=(xn,yn)是平面n上n个点构成的集合S,最近对就是找出集合S中距离最近的点对的算法分治法C语言代码
时间: 2024-09-24 11:03:42 浏览: 80
对于这个问题,我们需要考虑的是二维平面上的最近对点问题。由于涉及到了n个点,我们可以采用分治法结合排序的思想。这里是一个简单的C语言示例,我们使用了优先队列(堆)来优化搜索过程:
```c
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <limits.h>
// 定义结构体表示点
typedef struct Point {
int x, y;
} Point;
// 比较函数用于堆中排序
int compare(const void *a, const void *b) {
Point *pa = (Point *) a, *pb = (Point *) b;
return pa->y - pb->y; // 按y坐标升序排列,如果y相同再按x坐标升序
}
// 使用堆实现查找最近对点
void findNearestPair(Point points[], int n, int *min_dist, Point **nearest_pair) {
if (n <= 2) { // 基线情况,最少有三个点才有最近对
if (n == 2) {
*min_dist = manhattanDistance(points[0].x, points[0].y, points[1].x, points[1].y);
*nearest_pair = &points[0], *(nearest_pair + 1) = &points[1];
} else {
*min_dist = INT_MAX;
*nearest_pair = NULL;
}
return;
}
// 将点按照y坐标排序,x坐标相同则保持原顺序
qsort(points, n, sizeof(Point), compare);
// 初始化当前最近对的距高和对应点
int current_min = INT_MAX;
Point *current_nearest_pair = points;
for (int i = 0; i < n - 1; i++) {
int dist_to_right = manhattanDistance(points[i].x, points[i].y, points[i + 1].x, points[i + 1].y);
if (dist_to_right < current_min) {
current_min = dist_to_right;
current_nearest_pair = &points[i];
}
}
*min_dist = current_min;
*nearest_pair = current_nearest_pair;
// 再次遍历剩下的点,寻找不在排序链中的潜在最近对
for (int i = 0; i < n; i++) {
if (i == *nearest_pair) continue; // 跳过已知最近对
for (int j = i + 2; j < n; j++) {
if (manhattanDistance(points[i].x, points[i].y, points[j].x, points[j].y) < *min_dist) {
*min_dist = manhattanDistance(points[i].x, points[i].y, points[j].x, points[j].y);
*nearest_pair = &points[i];
}
}
}
}
int main() {
Point points[] = {{1, 3}, {2, 4}, {3, 5}, {4, 6}, {5, 7}};
int n = sizeof(points) / sizeof(points[0]);
int min_dist;
Point *nearest_pair;
findNearestPair(points, n, &min_dist, &nearest_pair);
printf("Minimum Manhattan distance: %d\n", min_dist);
printf("Nearest point pair: (%d, %d), (%d, %d)\n", nearest_pair->x, nearest_pair->y, points[(*nearest_pair).y].x, points[(*nearest_pair).y].y);
return 0;
}
// manhattanDistance函数用于计算两点间的曼哈顿距离
int manhattanDistance(int x1, int y1, int x2, int y2) {
return abs(x1 - x2) + abs(y1 - y2);
}
阅读全文