hdu 1007(最近点对)

 1 /*

 2 *  题目要求:求最近点对  

 3 */

 4 

 5 #include <cmath>

 6 #include <cstdio>

 7 #include <cstdlib>

 8 #include <iostream>

 9 #include <algorithm>

10 

11 using namespace std;

12 

13 const int N = 100005;

14 const double INF = 1e15;

15 

16 struct point {

17     double x;

18     double y;

19 }p[N];

20 int tmp[N];

21 

22 double dis(point A, point B) {

23     return sqrt((A.x-B.x)*(A.x-B.x)+(A.y-B.y)*(A.y-B.y));

24 }

25 

26 int cmp(const point &a, const point &b) {

27     if (a.x != b.x) return a.x < b.x;

28     return a.y < b.y;

29 }

30 

31 int cmp1(const int &a, const int &b) {

32     return p[a].y < p[b].y;

33 }

34 

35 double min(double a, double b) {

36     return a > b ? b : a;

37 }

38 

39 double closestPair(int left, int right) {

40     double d = INF;

41     if (left == right) return d;

42     if (left+1 == right) return dis(p[left], p[right]);

43     int mid = (left + right) >> 1;

44     double d1 = closestPair(left, mid);

45     double d2 = closestPair(mid+1, right);

46     d = min(d1, d2);

47     int k = 0;

48     for (int i=left; i<=right; ++i) {

49         if (fabs(p[mid].x- p[i].x) <= d) tmp[k++] = i;

50     }

51     sort(tmp, tmp+k, cmp1);

52     for (int i=0; i<k; ++i) {

53         for (int j=i+1; j<k && p[tmp[j]].y-p[tmp[i]].y<d; ++j) {

54             double d3 = dis(p[tmp[i]], p[tmp[j]]);

55             if (d3 < d) d = d3;

56         }

57     }

58     return d;

59 } 

60 

61 int main() {

62     int n;

63     while (scanf("%d", &n), n) {

64         for (int i=0; i<n; ++i) scanf ("%lf%lf", &p[i].x, &p[i].y);

65         sort(p, p+n, cmp);

66         double ans = closestPair(0, n-1) * 0.5;

67         printf ("%.2lf\n", ans); 

68     }

69     return 0;

70 }

 

你可能感兴趣的:(HDU)