uva 10245 - The Closest Pair Problem(暴力剪枝)

来源:互联网 发布:已连接,但无法访问网络 编辑:程序博客网 时间:2024/06/05 10:02

题目连接:10245 - The Closest Pair Problem


题目大意:给出若干个点,找出两个点,使得两点间距离为所有任意两点距离中的最小值。


解题思路:本来这题应该用分治的方法去做的,但是偷了点懒,暴力剪枝过了,剪枝的方法就是将所有点按照x的大小来排序,当point[j].x - point[i].x > min(min 为当前找到的最小值),可以跳出循环,开始判断i+ 1点。


#include <stdio.h>#include <string.h>#include <algorithm>#include <math.h>using namespace std;const int N = 100010;struct point {    double x;    double y;}p[N];bool cmp(const point &a, const point &b) {    return a.x < b.x;}double getDist(point a, point b) {    double tmpx = (a.x - b.x) * (a.x - b.x);    double tmpy = (a.y - b.y) * (a.y - b.y);    return sqrt(tmpx + tmpy);}int main() {    int n;    double Min, dist;    while (scanf("%d", &n), n) {memset(p, 0, sizeof(p));Min = 0XFFFFFFF;for (int i = 0; i < n; i++)    scanf("%lf %lf", &p[i].x, &p[i].y);sort(p, p + n, cmp);for (int i = 0; i < n; i++) {    for (int j = i + 1; j < n; j++) {if (fabs(p[i].x - p[j].x) - Min > 1e-9)    break;dist = getDist(p[i], p[j]);if (Min - dist > 1e-9)    Min = dist;    }}if (Min - 10000 > 1e-9)    printf("INFINITY\n");else    printf("%.4lf\n", Min);    }    return 0;}


原创粉丝点击