【洛谷】P1257 平面上的最接近点对

题目地址:

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 1n104 0 ≤ x , y ≤ 1 0 9 0 \leq x, y \leq 10^9 0x,y109,小数点后的数字个数不超过 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)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值