【算法实践】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;
}
发布了100 篇原创文章 · 获赞 142 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_44936889/article/details/104505356