POJ3714(分治)

题意是给你两堆点,求毎堆点各取一个的最近距离。

给毎个点一个属于标记,然后合并的时候判断是不是属于不同的两堆点。

#include <cstdio>
#include <cmath>
#include <algorithm>
using namespace std;
#define maxn 211111
#define INF 1e15

struct node {
    double x, y;
    bool belong;
} p[maxn], tmp[maxn];
int n;

bool cmp1 (const node &a, const node &b) {
    return a.x < b.x || (a.x == b.x && a.y < b.y);
}

bool cmp2 (const node &a, const node &b) {
    return a.y < b.y;
}

double dis (node a, node b) {
    double xx = a.x-b.x, yy = a.y-b.y;
    return sqrt (xx*xx + yy*yy);
}

double solve (int l, int r) {
    double d = INF;
    if (l == r)
        return d;
    if (r-l == 1) {
        if (p[l].belong^p[r].belong)
            return dis (p[l], p[r]);
        else
            return d;
    }
    int mid = (l+r)>>1;
    d = min (solve (l, mid), solve (mid+1, r));
    int cnt = 0;
    for (int i = l; i <= r; i++) {
        if (fabs (p[mid].x-p[i].x) < d) {
            tmp[cnt++] = p[i];
        }
    }
    sort (tmp, tmp+cnt, cmp2);
    for (int i = 0; i < cnt; i++) {
        for (int j = i+1; j < cnt && tmp[j].y-tmp[i].y < d; j++) {
            if (tmp[i].belong^tmp[j].belong)
                d = min (d, dis(tmp[i], tmp[j]));
        }
    }
    return d;
}

int main () {
    //freopen ("in", "r", stdin);
    int t;
    scanf ("%d", &t);
    while (t--) {
        scanf ("%d", &n);
        for (int i = 0; i < n; i++) {
            scanf ("%lf%lf", &p[i].x, &p[i].y);
            p[i].belong = 0;
        }
        for (int i = n; i < n+n; i++) {
            scanf ("%lf%lf", &p[i].x, &p[i].y);
            p[i].belong = 1;
        }
        n <<= 1;
        sort (p, p+n, cmp1);
        printf ("%.3f\n", solve (0, n-1));
    }
    return 0;
}


你可能感兴趣的:(POJ3714(分治))