题目地址:
https://www.luogu.com.cn/problem/P1257
题目描述:
给定平面上
n
n
n个点,找出其中的一对点的距离,使得在这
n
n
n个点的所有点对中,该距离为所有点对中最小的。
输入格式:
第一行一个整数
n
n
n,表示点的个数。
接下来
n
n
n行,每行两个整数
x
,
y
x,y
x,y ,表示一个点的行坐标和列坐标。
输出格式:
仅一行,一个实数,表示最短距离,四舍五入保留
4
4
4位小数。
数据范围:
对于
100
%
100\%
100%的数据,保证
1
≤
n
≤
1
0
4
1 \leq n \leq 10^4
1≤n≤104,
0
≤
x
,
y
≤
1
0
9
0 \leq x, y \leq 10^9
0≤x,y≤109,小数点后的数字个数不超过
6
6
6。
直接暴力做。另一个更好的方法是分治,参考https://blog.csdn.net/qq_46105170/article/details/132522884。代码如下:
#include <iostream>
#include <climits>
#include <cmath>
using namespace std;
const int N = 1e4 + 10;
int n;
struct Point {
double x, y;
} p[N];
double res;
int main() {
scanf("%d", &n);
for (int i = 1; i <= n; i++) scanf("%lf%lf", &p[i].x, &p[i].y);
res = numeric_limits<double>::max();
auto f = [](Point& p1, Point& p2) {
return (p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y);
};
for (int i = 1; i <= n; i++)
for (int j = i + 1; j <= n; j++)
res = min(res, f(p[i], p[j]));
printf("%.4lf\n", sqrt(res));
}
时间复杂度 O ( n 2 ) O(n^2) O(n2),空间 O ( 1 ) O(1) O(1)。