HDOJ 1007 Quoit Design
题目不难,按照最近点对的算法一步一步来就可以了,没什么陷阱,所以一次AC。另外在比较距离时做了小小的优化,只在需要的时候开平方,而不是直接返回平方根。最近点对问题,参考:http://www.cnblogs.com/AdaByron/archive/2011/10/07/2200966.html
以下代码仅供参考:
View Code
1 #include <algorithm>
2 using namespace std;
3 #include <stdio.h>
4 #include <math.h>
5 struct Point
6 {
7 double x;
8 double y;
9 };
10 int num;
11 Point points[100001];
12 Point assist[100001];
13
14 inline bool cmpx(Point a ,Point b )
15 {
16 return a.x < b.x;
17 }
18 inline bool cmpy(Point a ,Point b )
19 {
20 return a.y < b.y;
21 }
22 inline double space(Point a, Point b)
23 {
24 return (a.x - b.x)*(a.x - b.x) + (a.y - b.y)*(a.y - b.y);
25 }
26 inline double minBinary(double a,double b)
27 {
28 return a<b?a:b;
29 }
30 double binarySlove(int l,int r,Point* p)
31 {
32 if(r-l==1)
33 return space(p[l],p[r]);
34 if(r-l==2)
35 return minBinary(minBinary(space(p[l],p[l+1]),space(p[l],p[r])),space(p[l+1],p[r]));
36 int half=(l+r)/2;
37 double min=minBinary(binarySlove(l,half,p),binarySlove(half+1,r,p));
38 double sqrtMin=sqrt(min);
39 int cnt=0;
40 for (int i=l;i<=r;i++)
41 if(points[i].x<points[half].x+sqrtMin&&points[i].x>points[half].x-sqrtMin)
42 assist[cnt++]=points[i];
43 sort(assist,assist+cnt,cmpy);
44 for (int i=0;i<cnt;i++)
45 for (int j=i+1;j<cnt;j++)
46 {
47 if(assist[j].y-assist[i].y>sqrtMin)
48 break;
49 min=minBinary(min,space(assist[i],assist[j]));
50 }
51 return min;
52 }
53 int main()
54 {
55 //freopen("Quoit Design.txt","r",stdin);
56 while(scanf("%d",&num)!=EOF&&num)
57 {
58 int min=0;
59 for (int i=0;i<num;i++)
60 {
61 scanf("%lf%lf",&(points[i].x),&(points[i].y));
62 }
63 sort(points,points+num,cmpx);
64 double result=binarySlove(0,num-1,points);
65 printf("%.2lf\n",sqrt(result)/2);
66 }
67 return 0;
68 }