我有一条线说线 L, lx + my + n = 0
。现在,给定一些 K 点说,(x1,y1),(x2, y2)...(xk,yk)
是否在线 L 上的 xy 平面上,我想在线 L 上找到一个点,比如 X (x0,y0)
,使得 X 和“N”点之间的距离之和最小。解决这样一个问题的算法是什么。我想到了一个解决方案,首先我找到点的坐标与每个点的线 L 的垂直线相交(x1,y1),(x2, y2)...(xk,yk)
。然后我找到了所有这些点的平均点,其中垂线与线 L 相交以找到最小点。但这样的做法是错误的。请提出解决问题的正确方法。这是我的代码
#include <stdio.h>
#include <math.h>
typedef struct
{
int x;
int y;
}point;
double distance(point * A, double x, double y)
{
return sqrt(pow(A->x - x, 2) + pow(A->y - y, 2));
}
int main()
{
int i = 0 , j = 0, test = 0, number_of_warehouse = 0, A = 0, B = 0, C = 0;
point * point_array , *closest_points, sum;
double avgx = 0.0, avgy = 0.0, Total_dist = 0.0;
scanf("%d", &test);
while (test--)
{
scanf("%d", &number_of_warehouse);
point_array = malloc (sizeof(point) * number_of_warehouse);
closest_points = malloc (sizeof(point) * number_of_warehouse);
scanf("%d%d%d", &A, &B,&C);
sum.x = 0;
sum.y = 0;
avgx = 0;
avgy = 0;
for(i = 0; i < number_of_warehouse; ++i)
{
scanf("%d%d", &(point_array[i].x), &(point_array[i].y));
closest_points[i].x = (B*(B * point_array[i].x - A * point_array[i].y) - A *C)/ (A*A + B*B);
closest_points[i].y = (A*((-1)* B * point_array[i].x + A * point_array[i].y) - B *C)/ (A*A + B*B);
sum.x += closest_points[i].x;
sum.y += closest_points[i].y;
}
Total_dist = 0.0;
avgx = sum.x / number_of_warehouse;
avgy = sum.y / number_of_warehouse;
for(i = 0; i < number_of_warehouse; ++i)
{
Total_dist += distance(point_array + i, avgx, avgy);
}
printf("%.6f", Total_dist);
}
return 0;
}