之前第10篇有提过,利用分治法采用递归来实现最近对问题,代码如下:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <complex>
#include <iostream>
#define MAX 10
//采用分治法(采用递归)的编程实现求解最近对问题
//利用BCFP函数找到最近的两个点,并输出结果
//结构体
typedef struct
{
double x;
double y;
}Point;
//两点之间的距离
double Distance(Point p1, Point p2)
{
return sqrt(pow(p1.x - p2.x, 2) + pow(p1.y - p2.y, 2));
}
//合并点并更新最近点对
void Merge(Point strip[], int size, double D_min, Point* c1, Point* c2)
{
for (int i = 0; i < size; i++)
{
for (int j = i + 1; j < size && (strip[j].y - strip[i].y) < D_min; j++)
{
double dist = Distance(strip[i], strip[j]);
if (dist < D_min)
{
D_min = dist;
*c1 = strip[i];
*c2 = strip[j];
}
}
}
}
//求解最近对
void BFCP(Point p[], int n, Point* c1, Point* c2)
{
if (n <= 1)
{
*c1 = p[0];
*c2 = p[0];
return;
}
if (n == 2)
{
*c1 = p[0];
*c2 = p[1];
return;
}
int mid = n / 2;
Point p_mid = p[mid];
Point c1_left, c2_left;
Point c1_right, c2_right;
BFCP(p, mid, &c1_left, &c2_left);
BFCP(p + mid, n - mid, &c1_right, &c2_right);
double D_min = fmin(Distance(c1_left, c2_left), Distance(c1_right, c2_right));
if (Distance(c1_left, c2_left) < Distance(c1_right, c2_right))
{
*c1 = c1_left;
*c2 = c2_left;
}
else
{
*c1 = c1_right;
*c2 = c2_right;
}
Point strip[MAX];
int j = 0;
for (int i = 0; i < n; i++)
{
if (abs(p[i].x - p_mid.x) < D_min)
{
strip[j++] = p[i];
}
}
Merge(strip, j, D_min, c1, c2);
}
int main()
{
int n;
printf("请输入你要输入的点的个数:");
scanf("%d", &n);
Point p[MAX];
for (int i = 0; i < n; i++)
{
printf("请输入x值:", i + 1);
scanf("%lf", &p[i].x);
printf("请输入y值:", i + 1);
scanf("%lf", &p[i].y);
}
Point c1, c2;
BFCP(p, n, &c1, &c2);
printf("最近的两个点是:(%.2f, %.2f) 和 (%.2f, %.2f)\n", c1.x, c1.y, c2.x, c2.y);
return 0;
}