【算法实践】1.2 套圈(分治,点集最小距离)

在这里插入图片描述
Have you ever played quoit in a playground? Quoit is a game in which flat rings are pitched at some toys, with all the toys encircled awarded.
In the field of Cyberground, the position of each toy is fixed, and the ring is carefully designed so it can only encircle one toy at a time. On the other hand, to make the game look more attractive, the ring is designed to have the largest radius. Given a configuration of the field, you are supposed to find the radius of such a ring.
Assume that all the toys are points on a plane. A point is encircled by the ring if the distance between the point and the center of the ring is strictly less than the radius of the ring. If two toys are placed at the same point, the radius of the ring is considered to be 0.

两个教训:

  1. 一定要规范数据类型,一开始用 float 的坐标去算 double 的距离,精度丢失导致 WA;
  2. 一定要注意使用简单计算,一开始使用了 pow 计算平方,果断超时;
#include "stdio.h"

#include "algorithm"

#include "math.h"

using namespace std;

#define N 100005

struct Point
{
    double x, y;
} points[N];

Point id[N];

int sort_x(Point p1, Point p2)
{
    return p1.x < p2.x;
}

int sort_y(Point p1, Point p2)
{
    return p1.y < p2.y;
}

double dist(Point p1, Point p2)
{
    return sqrt((p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y));
}

double nearest(int l, int r)
{
    double d;
    if (l == r)
    {        return 10e100;
    }
    else if (l + 1 == r)
    {
        return dist(points[l], points[r]);
    }
    int m = (l + r) / 2;
    d = min(nearest(l, m), nearest(m + 1, r));
    // 挑选出合并时可能存在的最小邻近点的集合(保留索引)
    int n = 0, i;
    for (i = l; i <= r; i++)
    {
        if (fabs(points[i].x - points[m].x) <= d)
        {
            id[n++] = points[i];
        }
    }
    // 对索引按 y 排序(有重复的)
    sort(id, id + n, sort_y);
    for (int i = 0; i < n; i++)
    {
        for (int j = i + 1; j < n; j++)
        {
            if (id[j].y - id[i].y < d)
            {
                d = min(dist(id[i], id[j]), d);
            }
            else
            {
                break;
            }
        }
    }
    return d;
}

int main(int argc, char const *argv[])
{
    int n;
    double ans;
    while (true)
    {
        scanf("%d", &n);
        if (n == 0)
        {
            break;
        }
        for (int i = 0; i < n; i++)
        {
            scanf("%lf %lf", &points[i].x, &points[i].y);
        }
        sort(points, points + n, sort_x);
        ans = nearest(0, n - 1);
        printf("%.2lf\n", ans / 2);
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

BIT可达鸭

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值