hdu1007 平面最近点问题

http://acm.hdu.edu.cn/showproblem.php?pid=1007

 

 

 

 

 

题意:即给定坐标系上N个点,找到距离最短的两个点。

 

参考博客:https://www.cnblogs.com/zyxStar/p/4591897.html

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
const double inf = 1e20;
const int maxn = 100005;

struct Point {
    double x, y;
}point[maxn];

int n, mpt[maxn];


//以x为基准排序
bool cmpxy(const Point& a, const Point& b) {
    if (a.x != b.x)
        return a.x < b.x;
    return a.y < b.y;
}

bool cmpy(const int& a, const int& b) {
    return point[a].y < point[b].y;
}

double min(double a, double b) {
    return a < b ? a : b;
}
//求两点距离
double dis(int i, int j) {
    return sqrt((point[i].x - point[j].x)*(point[i].x - point[j].x) + (point[i].y - point[j].y)*(point[i].y - point[j].y));
}
//将平面二分为左右两个点集,分别找平面左右两边中最短的距离d
//然后再把平面区间在[left,right]范围内的点中,把p.x到中点mid距离小于d的点标记
//被标记的点按x坐标再次排序
//两个for遍历这个点集,更新最小距离d
double Closest_Pair(int left, int right) {
    double d = inf;
    if (left == right)
        return d;
    if (left + 1 == right)
        return dis(left, right);
    int mid = (left + right) >> 1;
    double d1 = Closest_Pair(left, mid);
    double d2 = Closest_Pair(mid + 1, right);
    d = min(d1, d2);
    int i, j, k = 0;
    //分离出宽度为d的区间
    for (i = left; i <= right; i++) {
        if (fabs(point[mid].x - point[i].x) <= d)
            mpt[k++] = i;
    }
    sort(mpt, mpt + k, cmpy);
    //线性扫描
    for (i = 0; i < k; i++) {
        for (j = i + 1; j < k && point[mpt[j]].y - point[mpt[i]].y < d; j++) {
            double d3 = dis(mpt[i], mpt[j]);
            if (d > d3)    d = d3;
        }
    }
    return d;
}

int main() {
    while (~scanf("%d", &n) && n) {
        for (int i = 0; i < n; i++)
            scanf("%lf %lf", &point[i].x, &point[i].y);
        sort(point, point + n, cmpxy);
        printf("%.2lf\n", Closest_Pair(0, n - 1) / 2);
    }
    return 0;
}

 

posted @ 2020-06-21 22:22  知道了呀~  阅读(357)  评论(0编辑  收藏  举报