uva 10245 The Closest Pair Problem

题意:求最短距离的一对点的距离,枚举每种情况就行了,可以优化的地方是我们按X的坐标从小到大排序,一旦出现a.x-b.x的绝对值大于Min的话,那么接下来的就不用再计算了

#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <algorithm>
using namespace std;
const int MAXN = 10005;

struct point
{
    double x,y;
}arr[MAXN];

int cmp(point a,point b)
{
    return a.x < b.x;
}

int main()
{
    int n;
    while (scanf("%d",&n) != EOF && n)
    {
        double Min = 10000;
        for (int i = 0; i < n; i++)
            scanf("%lf %lf",&arr[i].x,&arr[i].y);
        sort(arr,arr+n,cmp);

        for (int i = 0; i < n; i++)
        {
            for (int j = i + 1; j < n; j++)
            {
                double dis1 = arr[i].x - arr[j].x;
                double dis2 = arr[i].y - arr[j].y;
                double dis = sqrt(dis1*dis1 + dis2*dis2);
                if (abs(arr[j].x - arr[i].x) >= Min)
                    break;
                if (dis < Min)
                    Min = dis;
            }
        }
        if (Min >= 10000)
            printf("INFINITY\n");  
        else printf("%.4lf\n",Min);
    }
    return 0;
}



你可能感兴趣的:(uva 10245 The Closest Pair Problem)