HDU-1007

这个看了网上的题解,应该不是O(n*log(n))的复杂度,那个两重循环是有优化的可能的,应该只用检查附近的6个点就行了。

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <ctime>
#include <iostream>
#include <algorithm>
using namespace std;
struct P
{
    double x, y;
    P() {}
    P(double x, double y) : x(x), y(y) {}
    P operator =(P p)
    {
        x = p.x, y = p.y;
        return *this;
    }
};
P ans_arr[100117], in_arr[100117];

bool cmpx(P a, P b)
{
    return a.x < b.x;
}

bool cmpy(P a, P b)
{
    return a.y < b.y;
}

double get_dist(P a, P b)
{
    return ((a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y));
}

double nearest_pair(int l, int r)
{
    if(r == l + 1) return get_dist(in_arr[l], in_arr[r]);
    else if(r == l + 2) return min(get_dist(in_arr[l], in_arr[l + 1]), min(get_dist(in_arr[l], in_arr[r]), get_dist(in_arr[l + 1], in_arr[r])));
    else
    {
        int mid = (l + r) >> 1, cnt = 0;
        double ans = min(nearest_pair(l, mid), nearest_pair(mid + 1, r));
        for(int i = l; i <= r; ++i)
        {
            if(in_arr[mid].x - ans <= in_arr[i].x && in_arr[i].x <= in_arr[mid].x)
            {
                ans_arr[cnt++] = in_arr[i];
            }
        }
        sort(ans_arr, ans_arr + cnt, cmpy);
        for(int i = 0; i < cnt; ++i)
        {
            for(int j = i + 1; j < cnt; ++j)
            {
                double tmp = get_dist(ans_arr[i], ans_arr[j]);
                if(tmp > ans) break;
                ans = tmp;
            }
        }
        return ans;
    }
}

int main()
{
//    freopen("in.in", "r", stdin);
    int n;
    while(scanf("%d", &n) != EOF && n != 0)
    {
        memset(in_arr, 0, sizeof(in_arr));
        memset(ans_arr, 0, sizeof(ans_arr));
        for(int i = 0; i < n; ++i)
        {
            scanf("%lf %lf", &in_arr[i].x, &in_arr[i].y);
        }
        sort(in_arr, in_arr + n, cmpx);
        printf("%.2lf\n", sqrt(nearest_pair(0, n - 1)) / 2.0);
    }
return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值