洛谷 P1429 平面最近点对(加强版)

洛谷 P1429 平面最近点对(加强版)

Description

  • 给定平面上n个点,找出其中的一对点的距离,使得在这n个点的所有点对中,该距离为所有点对中最小的

Input

  • 第一行:n;2≤n≤200000

    接下来n行:每行两个实数:x y,表示一个点的行坐标和列坐标,中间用一个空格隔开。

Output

  • 仅一行,一个实数,表示最短距离,精确到小数点后面4位。

Sample Input

3
1 1
1 2
2 2

Sample Output

1.0000

Data Size

  • 0<=x,y<=10^9

题解:

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
#define N 200005
#define inf 0x7fffffff
using namespace std;

struct A {double x, y;} a[N];
int n;
int t[N];

bool cmp1(A u, A v) {return u.x < v.x;}
bool cmp2(int u, int v) {return a[u].y < a[v].y;}
double cal(int u, int v)
{
    double v1 = (a[u].x - a[v].x) * (a[u].x - a[v].x);
    double v2 = (a[u].y - a[v].y) * (a[u].y - a[v].y);
    return sqrt(v1 + v2);
}

double fun(int l, int r)
{
    if(l == r) return inf;
    if(l + 1 == r) return cal(l, r);
    int mid = (l + r) >> 1, cnt = 0;
    double d = min(fun(l, mid), fun(mid + 1, r));
    for(int i = l; i <= r; i++)
        if(fabs(a[i].x - a[mid].x) < d)
            t[++cnt] = i;
    sort(t + 1, t + 1 + cnt, cmp2);
    for(int i = 1; i < cnt; i++)
        for(int j = i + 1; j <= cnt; j++)
            if(a[t[j]].y - a[t[i]].y >= d) break;
            else d = min(d, cal(t[i], t[j]));
    return d;
}

int main()
{
    cin >> n;
    for(int i = 1; i <= n; i++)
        scanf("%lf%lf", &a[i].x, &a[i].y);
    sort(a + 1, a + 1 + n, cmp1);
    printf("%.4lf\n", fun(1, n));
    return 0;
}

转载于:https://www.cnblogs.com/BigYellowDog/p/11628255.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值