COJ 1251最近点对(模板题)

[007]【算法实验项目】最近点对

Time Limit: 3000 ms     Memory Limit: 65536 KB
Total Submit: 19     Accepted: 6

Description
平面上有一系列点,请求出最近两点之间的距离

Input
第一行是一个整数T,表示测试数据个数
接下来对于每个测试数据输入一个正整数N,表示点的数个(2 <= N <= 100000)
接下来N行输入两个整数x,y表示每个点的坐标 (0< x , y < 10000)

Output
对于每个测试数据输出最近两点之间的距离,保留小数点后两位

Sample Input
2
2
0 0
1 1
2
1 1
1 1

Sample Output
1.41
0.00

Hint
推荐分治法求解

Source
《算法设计与分析》

#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
using namespace std;
struct point
{
    double x , y;
} p[100005];
int a[100005];
int cmpx(const point &a , const point &b)
{
    return a.x < b.x;
}
int cmpy(int a , int b)
{
    return p[a].y < p[b].y;
}
inline double dis(point &a , point &b)
{
    return sqrt( (a.x-b.x)*(a.x-b.x) + (a.y-b.y)*(a.y-b.y));
}
inline double min(double a , double b)
{
    return a < b ? a : b;
}
double closest(int low , int high)
{
    if(low + 1 == high) return dis(p[low] , p[high]);
    if(low + 2 == high)
        return min(dis(p[low],p[high]),min(dis(p[low],p[low+1]),dis(p[low+1],p[high])));
    int mid = (low + high)>>1;
    double ans = min( closest(low , mid) , closest(mid + 1 , high) );
    int i , j , cnt = 0;
    for(i = low ; i <= high ; ++i)
        if(p[i].x >= p[mid].x - ans && p[i].x <= p[mid].x + ans)
            a[cnt++] = i;
    sort(a,a + cnt,cmpy);
    for(i = 0 ; i < cnt ; ++i)
        for(j = i+1 ; j < cnt ; ++j)
        {
            if(p[a[j]].y - p[a[i]].y >= ans) break;
            ans = min(ans , dis(p[a[i]] , p[a[j]]));
        }
    return ans;
}
int main()
{
    int i,n,m;
    cin>>m;
    while(m--)
    {
        cin>>n;
        for(i = 0 ; i < n ; i++)
            scanf("%lf %lf",&p[i].x,&p[i].y);
        sort(p , p + n , cmpx);
        printf("%.2f\n",closest(0 , n - 1));
    }
    return 0;
}


你可能感兴趣的:(COJ 1251最近点对(模板题))