hdu 1007 N个点中输出2点的最小距离的一半

分治法

Sample Input
2
0 0
1 1
2
1 1
1 1
3
-1.5 0
0 0
0 1.5
0

Sample Output
0.71
0.00
0.75

 

 1 # include <iostream>
 2 # include <cstdio>
 3 # include <cstring>
 4 # include <algorithm>
 5 # include <string>
 6 # include <cmath>
 7 # include <queue>
 8 # include <list>
 9 # define LL long long
10 using namespace std ;
11 
12 const double eps = 1e-6;
13 const int MAXN = 100010;
14 const double INF = 1e20;
15 struct Point
16 {
17    double x,y;
18 };
19 
20 double dist(Point a,Point b)
21 {
22    return sqrt((a.x-b.x)*(a.x-b.x) + (a.y-b.y)*(a.y-b.y));
23 }
24 
25 Point p[MAXN];
26 Point tmpt[MAXN];
27 bool cmpxy(Point a,Point b)
28 {
29     if(a.x != b.x)return a.x < b.x;
30     else return a.y < b.y;
31 }
32 bool cmpy(Point a,Point b)
33 {
34     return a.y < b.y;
35 }
36 double Closest_Pair(int left,int right)
37 {
38     double d = INF;
39     if(left == right)return d;
40     if(left + 1 == right)
41     return dist(p[left],p[right]);
42     int mid = (left+right)/2;
43     double d1 = Closest_Pair(left,mid);
44     double d2 = Closest_Pair(mid+1,right);
45     d = min(d1,d2);
46     int k = 0;
47     for(int i = left;i <= right;i++)
48     {
49         if(fabs(p[mid].x - p[i].x) <= d)
50         tmpt[k++] = p[i];
51     }
52     sort(tmpt,tmpt+k,cmpy);
53     for(int i = 0;i <k;i++)
54     {
55         for(int j = i+1;j < k && tmpt[j].y - tmpt[i].y < d;j++)
56         {
57             d = min(d,dist(tmpt[i],tmpt[j]));
58         }
59     }
60     return d;
61 }
62 
63 int main()
64 {
65     //freopen("in.txt","r",stdin) ;
66     int n;
67     while(scanf("%d",&n)==1 && n)
68     {
69         for(int i = 0;i < n;i++)
70         scanf("%lf%lf",&p[i].x,&p[i].y);
71         sort(p,p+n,cmpxy);
72         printf("%.2lf\n",Closest_Pair(0,n-1)/2);
73     }
74     return 0;
75 }
View Code

 

posted @ 2015-10-11 19:29  __Meng  阅读(236)  评论(0编辑  收藏  举报