题目:平面上有n个点,求所有各点之间的最长距离。
#include <stdio.h>
#include <stdlib.h>
#include <float.h>
typedef struct {
double x, y;
} Point;
int comparePoints(const void *a, const void *b) {
Point *p1 = (Point *)a;
Point *p2 = (Point *)b;
if (p1->x != p2->x) {
return (p1->x < p2->x) ? -1 : 1;
} else {
return (p1->y < p2->y) ? -1 : 1;
}
}
double distance(Point p1, Point p2) {
double dx = p1.x - p2.x;
double dy = p1.y - p2.y;
return sqrt(dx * dx + dy * dy);
}
double longestDistance(Point points[], int n) {
if (n <= 1) return 0;
qsort(points, n, sizeof(Point), comparePoints);
double maxDist = 0;
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
double d = distance(points[i], points[j]);
if (d > maxDist) {
maxDist = d;
}
if (d < maxDist && j != n - 1) {
break;
}
}
}
double lastToFirst = distance(points[0], points[n - 1]);
if (lastToFirst > maxDist) {
maxDist = lastToFirst;
}
return maxDist;
}
int main() {
Point points[] = {{1, 2}, {2, 3}, {4, 5}, {7, 8}, {0, 0}};
int n = sizeof(points) / sizeof(points[0]);
double longest = longestDistance(points, n);
printf("最长距离为: %.2f\n", longest);
return 0;
}