Language:
Bridge Across Islands
Description Thousands of thousands years ago there was a small kingdom located in the middle of the Pacific Ocean. The territory of the kingdom consists two separated islands. Due to the impact of the ocean current, the shapes of both the islands became convex polygons. The king of the kingdom wanted to establish a bridge to connect the two islands. To minimize the cost, the king asked you, the bishop, to find the minimal distance between the boundaries of the two islands. Input The input consists of several test cases. Output For each test case output the minimal distance. An error within 0.001 is acceptable. Sample Input 4 4 0.00000 0.00000 0.00000 1.00000 1.00000 1.00000 1.00000 0.00000 2.00000 0.00000 2.00000 1.00000 3.00000 1.00000 3.00000 0.00000 0 0 Sample Output 1.00000 |
题意:给出两个多边形求他们之间最小距离
题中没说但后台数据应该是按照逆时针数据给出的所以不用再求凸包;
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<algorithm>
#define eps 1e-8
#define inf 0x3f3f3f3f
using namespace std;
struct point{
double x,y;
}A[10010],B[10010];
double MIN(double a,double b){
return a<b?a:b;
}
double dist(point a,point b){//求两点间距离
return sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y));
}
double dotp(point p0,point p1,point p2){//点积
return (p1.x-p0.x)*(p2.x-p0.x)+(p1.y-p0.y)*(p2.y-p0.y);
}
double cp(point p0,point p1,point p2){//叉积
return (p1.x-p0.x)*(p2.y-p0.y)-(p1.y-p0.y)*(p2.x-p0.x);
}
double pld(point p1,point p2,point p3){//点线距
if(dist(p1,p2)<eps)return dist(p2,p3);
if(dotp(p1,p2,p3)+eps<0)return dist(p1,p3);
if(dotp(p2,p1,p3)+eps<0)return dist(p2,p3);
return fabs(cp(p1,p2,p3)/dist(p1,p2));
}
double lld(point p1,point p2,point p3,point p4){//线线距
return MIN(MIN(pld(p1,p2,p3),pld(p1,p2,p4)),MIN(pld(p3,p4,p1),pld(p3,p4,p2)));
}
double rotating_calipers(point *p,point *q,int n,int m){//旋转卡壳
int i,d=0,u=0;
p[n]=p[0];q[m]=q[0];
for(int i=0;i<n;++i){
if(p[i].y<p[d].y)d=i;//y值最小点
}
for(int i=0;i<m;++i){//y值最大点
if(q[i].y>q[u].y)u=i;
}
double ans=inf;
for(i=0;i<n;++i){
double cnt;
while(cnt=cp(p[d+1],q[u+1],p[d])-cp(p[d+1],q[u],p[d])>eps)u=(u+1)%m;
if(cnt+eps<0)ans=MIN(ans,pld(p[d],p[d+1],q[u]));
else ans=MIN(ans,lld(p[d],p[d+1],q[u],q[u+1]));
d=(d+1)%n;
}
return ans;
}
int main()
{
int i,n,m;
while(scanf("%d%d",&n,&m),n||m){
for(i=0;i<n;++i){
scanf("%lf%lf",&A[i].x,&A[i].y);
}
for(i=0;i<m;++i){
scanf("%lf%lf",&B[i].x,&B[i].y);
}
printf("%.5lf\n",MIN(rotating_calipers(A,B,n,m),rotating_calipers(B,A,m,n)));
}
return 0;
}