【分治 求最近點對】hdu 1007 Quoit Design

CN_swords發表於2017-08-19

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

#include <bits/stdc++.h>
using namespace std;
/*
hdu 1007
題意:給出物品在平面上的點座標,求一個環不能一次套到兩的最大半徑,即最近點對距離的一半。
題解:先以x排序,用分治將問題分成左邊部分的最近點對,和左邊的最近點對,左邊右邊各一個點的
最近點對(在算這個的時候應按y排序,將兩點y差大於當前最小值的優化掉)。
*/
const int N = 1e5+5;
const double INF = 1e18;
struct Point{double x,y; } a[N];
bool cmp(Point a,Point b){return a.x < b.x; }
bool cmp2(Point a,Point b){return a.y < b.y; }
double dist(Point a,Point b){return sqrt((a.y-b.y)*(a.y-b.y)+(a.x-b.x)*(a.x-b.x))/2; }
Point temp[N];
double solve(int l, int r){
    if(l == r)
        return INF;
    int mid = (l+r)>>1;
    double mi;
    mi = solve(l,mid);
    mi = min(mi,solve(mid+1,r));
//    printf("L=%f R=%f\n",solve(l,mid),solve(mid+1,r));
    int top = 0;
    temp[top++] = a[mid];
    for(int i = mid-1; i >= l; i--){
        if(a[mid].x-a[i].x>=mi)
            break;
        temp[top++] = a[i];
    }
    for(int i = mid+1; i <= r; i++){
        if(a[i].x-a[mid].x>=mi)
            break;
        temp[top++] = a[i];
    }
    sort(temp,temp+top,cmp2);
    for(int i = 0; i < top; i++){
        for(int j = i+1; j < top; j++)
        {
            if(temp[j].y-temp[i].y>=mi)
                break;
            mi = min(mi,dist(temp[i],temp[j]));
        }
    }
    return mi;
}
int main()
{
    int n;
    while(~scanf("%d",&n) && n)
    {
        for(int i = 0; i < n; i++)
            scanf("%lf%lf",&a[i].x,&a[i].y);
        sort(a,a+n,cmp);
        printf("%.2f\n",solve(0,n-1));
    }
    return 0;
}


相關文章