hdu_1007_Quoit Design(最近点对)

题目连接:hdu_1007_Quoit Design

题意:

给你平面上的一些点,让你找出这些点的最近点对的距离

题解:
采用分治,达到O(nlognlogn)的时间复杂度就能艹过去了

 1 #include<stdio.h>
 2 #include<string.h>
 3 #include<algorithm>
 4 #include<math.h>
 5 using namespace std;
 6 //O(nlognlogn)找最近点对
 7 const int N=1e5+7;
 8 struct TPoint
 9 {
10     double x,y;
11 }ply[N],ans[N];
12 int n;
13 inline double MIN(double a,double b) {return a<b?a:b;}
14 bool cmpx(TPoint a,TPoint b) {return a.x<b.x;}
15 bool cmpy(TPoint a,TPoint b) {return a.y<b.y;}
16 double dist(TPoint a,TPoint b)
17 {
18     double s1=a.x-b.x;
19     double t1=a.y-b.y;
20     return sqrt(s1*s1+t1*t1);
21 }
22 double closest(int l,int r)
23 {
24     if(l+1==r) return dist(ply[l],ply[r]);//2点
25     else if(l+2==r)//三点
26         return MIN(dist(ply[l],ply[l+1]),MIN(dist(ply[l],ply[r]),dist(ply[l+1],ply[r])));
27     int i,j,mid,cnt;
28     mid=(l+r)>>1;
29     double mi=MIN(closest(l,mid),closest(mid+1,r));//递归解决
30     for(i=l,cnt=0;i<=r;i++)//相邻点符合
31     {
32         if(fabs(ply[i].x-ply[mid].x)<=mi)
33             ans[cnt++]=ply[i];
34     }
35     sort(ans,ans+cnt,cmpy);//按y排序
36     for(i=0;i<cnt;i++)for(j=i+1;j<cnt;j++)//更新最小距离
37     {
38         if(ans[j].y-ans[i].y>=mi) break;
39         mi=MIN(mi,dist(ans[i],ans[j]));
40     }
41     return mi;
42 }
43 int main()
44 {
45     while(scanf("%d",&n),n)
46     {
47         int i;
48         for(i=0;i<n;i++) scanf("%lf%lf",&ply[i].x,&ply[i].y);//输入点
49         sort(ply,ply+n,cmpx);//按x排序
50         double mi=closest(0,n-1);
51         printf("%.2lf\n",mi/2);
52     }
53     return 0;
54 }
View Code

 

posted @ 2016-07-19 11:08  bin_gege  阅读(201)  评论(0编辑  收藏  举报