POJ 3714 Raid 最近点对 扫描线

题意:


有N个士兵,N个炮台。给出这2N个点的坐标,求士兵距离炮台的最近距离。

思路:前面用分治法解决了这个问题,但是这个问题还能通过扫描线的方式进行乱搞,但是中间检查的范围是和分治法一样的。

          首先按照x坐标进行排序,然后在map中我们实时维护和当前点的x坐标差不大于d的点的集合。

          因为map中是按照y坐标有序的排列的,我们用lower_bound找到当前点的y坐标的下界y-d,然后检查y-d <= y <= y+d范围内的点就行了。

代码如下:

#include <cstdio>
#include <algorithm>
#include <set>
#include <cmath>

using namespace std;

const int MAX = 300010;

int T,N;

struct point{
    double x,y;
    int id;
    point(){}
    point(double xx, double yy, int i):x(xx),y(yy),id(id){}

    bool operator < (const point & rhs) const{
        return y < rhs.y;
    }
} points[MAX];

bool cmp(const point & lhs, const point & rhs)
{
    return lhs.x < rhs.x;
}

int main(void)
{
    //freopen("input.txt","r",stdin);
    scanf("%d",&T);
    while(T--){
        scanf("%d",&N);
        for(int i = 0; i < N; ++i){
            scanf("%lf%lf",&points[i].x,&points[i].y);
            points[i].id = 0;
        }
        for(int i = 0; i < N; ++i){
            scanf("%lf%lf",&points[i+N].x,&points[i+N].y);
            points[i].id = 1;
        }
        sort(points,points + 2 * N,cmp);
        int j = 0;
        double d = 0x6f6f6f6f;
        multiset<point> S;
        multiset<point>::iterator it;
        for(int i = 0; i < 2 * N; ++i){
            double x = points[i].x, y = points[i].y;
            while(j < i && (x - points[j].x > d))
                S.erase(points[j++]);
            for(it = S.lower_bound(point(x,y - d,0));
                it != S.end() && it->y <= y + d;
                ++it){
                double dx = x - it->x;
                double dy = y - it->y;
                if(it->id != points[i].id)
                    d = min(d,sqrt(dx * dx + dy * dy));
            }
            S.insert(points[i]);
        }
        printf("%.3f\n",d);
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值