poj3714Raid(平面最近点对)
模板 稍加一点标记
1 #include <iostream> 2 #include<cstdio> 3 #include<cstring> 4 #include<algorithm> 5 #include<stdlib.h> 6 #include<vector> 7 #include<cmath> 8 #include<queue> 9 #include<set> 10 using namespace std; 11 #define N 200010 12 #define LL long long 13 #define INF 0xfffffff 14 const double eps = 1e-8; 15 const double pi = acos(-1.0); 16 const double inf = ~0u>>2; 17 struct point 18 { 19 double x,y; 20 int id; 21 int flag; 22 point(double x=0,double y =0):x(x),y(y){} 23 }p[N],pp[N],py[N]; 24 typedef point pointt; 25 pointt operator -(point a,point b) 26 { 27 return point(a.x-b.x,a.y-b.y); 28 } 29 double dis(point a,point b) 30 { 31 if(a.flag==b.flag) return INF; 32 return sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y)); 33 } 34 bool cmp(point a,point b) 35 { 36 return a.x<b.x; 37 } 38 bool cmpp(point a,point b) 39 { 40 return a.y<b.y; 41 } 42 void binmerge(point py[],point pp[],int l,int m,int r) 43 { 44 int i,j,g=l; 45 for(i = l,j = m+1 ; i <= m&&j <= r ;) 46 if(pp[i].y<pp[j].y) py[g++] = pp[i++]; 47 else py[g++] = pp[j++]; 48 49 while(i<=m) py[g++] = pp[i++]; 50 while(j<=r) py[g++] = pp[j++]; 51 memcpy(pp + l, py + l, (r - l + 1) *sizeof(py[0])); 52 } 53 double binshortest(point p[],point pp[],point py[],int l,int r) 54 { 55 if(r-l==1) return dis(p[l],p[r]); 56 if(r-l==2) return min(min(dis(p[l],p[r]),dis(p[l],p[l+1])),dis(p[l+1],p[r])); 57 int mid = (l+r)>>1; 58 int i,j,g = l,o = mid+1; 59 for(i = l ; i <= r ; i++) 60 { 61 if(py[i].id<=mid)//按y坐标顺序将点划分到pp左半数组 62 pp[g++] = py[i]; 63 else 64 pp[o++] = py[i];//pp右半数组 65 } 66 double minz = min(binshortest(p,py,pp,l,mid),binshortest(p,py,pp,mid+1,r)); 67 binmerge(py,pp,l,mid,r); 68 g = l; 69 for(i = l ; i <= r ; i++) 70 if(fabs(py[i].x-py[mid].x)<minz) pp[g++] = py[i]; 71 for(i = l ; i < g ; i++) 72 { 73 for(j = i+1 ; j < g && fabs(pp[i].y-pp[j].y)<minz; j++) 74 minz = min(dis(pp[i],pp[j]),minz); 75 } 76 return minz; 77 } 78 int main() 79 { 80 int n,i,t; 81 cin>>t; 82 while(t--) 83 { 84 scanf("%d",&n); 85 for(i = 0; i < n; i++) 86 { 87 scanf("%lf%lf",&p[i].x,&p[i].y); 88 p[i].flag = 1; 89 } 90 for(i = n; i < n*2; i++) 91 { 92 scanf("%lf%lf",&p[i].x,&p[i].y); 93 p[i].flag = 2; 94 } 95 n<<=1; 96 sort(p,p+n,cmp); 97 for(i = 0;i < n ;i++) 98 p[i].id = i; 99 memcpy(py,p,n*sizeof(py[0])); 100 sort(p,p+n,cmpp); 101 double ans = binshortest(p,pp,py,0,n-1); 102 printf("%.3f\n",ans); 103 } 104 return 0; 105 }