#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
using namespace std;
// 定义一个点的结构体,包含x和y坐标
struct Point {
double x;
double y;
};
// 比较两个点的x坐标,用于按x排序
bool compare_x(const Point& a, const Point& b) {
return a.x < b.x;
}
// 比较两个点的y坐标,用于按y排序
bool compare_y(const Point& a, const Point& b) {
return a.y < b.y;
}
// 计算两个点之间的欧几里得距离
double distance(const Point& a, const Point& b) {
return sqrt((a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y));
}
// 用分治法求解最接近点对问题,返回最小距离和对应的点对
pair<double, pair<Point, Point>> closest_pair(vector<Point>& points, int left, int right) {
// 如果只有一个点,返回无穷大距离和空点对
if (left == right) {
return {INFINITY, {{0, 0}, {0, 0}}};
}
// 如果只有两个点,直接返回它们的距离和点对
if (left + 1 == right) {
return {distance(points[left], points[right]), {points[left], points[right]}};
}
// 如果有三个点,分别计算三种组合的距离,返回最小的那个
if (left + 2 == right) {
double d1 = distance(points[left], points[left + 1]);
double d2 = distance(points[left + 1], points[right]);
double d3 = distance(points[left], points[right]);
if (d1 <= d2 && d1 <= d3) {
return {d1, {points[left], points[left + 1]}};
}
if (d2 <= d1 && d2 <= d3) {
return {d2, {points[left + 1], points[right]}};
}
return {d3, {points[left], points[right]}};
}
// 如果有四个或以上的点,按照分治法进行递归求解
// 找到中间位置,将点集分为左右两部分
int mid = (left + right) / 2;
// 分别求解左右两部分的最接近点对和最小距离
auto left_result = closest_pair(points, left, mid);
auto right_result = closest_pair(points, mid + 1, right);
// 取左右两部分中较小的距离和对应的点对
double min_dist = min(left_result.first, right_result.first);
auto min_pair = left_result.first < right_result.first ? left_result.second : right_result.second;
// 在左右两部分中找出x坐标在[mid - min_dist, mid + min_dist]范围内的点,并按y坐标排序
vector<Point> strip;
for (int i = left; i <= right; i++) {
if (abs(points[i].x - points[mid].x) < min_dist) {
strip.push_back(points[i]);
}
}
sort(strip.begin(), strip.end(), compare_y);
// 遍历这些点,找出是否有比min_dist更小的距离和对应的点对
for (int i = 0; i < strip.size(); i++) {
for (int j = i + 1; j < strip.size() && strip[j].y - strip[i].y < min_dist; j++) {
double dist = distance(strip[i], strip[j]);
if (dist < min_dist) {
min_dist = dist;
min_pair = {strip[i], strip[j]};
}
}
}
// 返回最终的结果
return {min_dist, min_pair};
}
int main() {
// 生成一些随机的点
vector<Point> points;
srand(time(NULL));
for (int i = 0; i < 10; i++) {
points.push_back({rand() % 100, rand() % 100});
}
// 按x坐标排序
sort(points.begin(), points.end(), compare_x);
// 输出所有的点
cout << "所有的点为:" << endl;
for (auto p : points) {
cout << "(" << p.x << ", " << p.y << ")" << endl;
}
// 调用分治法求解最接近点对问题
auto result = closest_pair(points, 0, points.size() - 1);
// 输出最小距离和对应的点对
cout << "最小距离为:" << result.first << endl;
cout << "对应的点对为:(" << result.second.first.x << ", " << result.second.first.y << ") 和 ("
<< result.second.second.x << ", " << result.second.second.y << ")" << endl;
return 0;
}