赞
踩
首先判断点是否在多边形上,然后求点到多边形每条边的最短距离
代码如下:
- #include<iostream>
- #include<algorithm>
- #include<string>
- #include<stack>
- #include<queue>
- #include<set>
- #include<map>
- #include<stdio.h>
- #include<stdlib.h>
- #include<ctype.h>
- #include<time.h>
- #include<math.h>
-
-
- #define N 105
- #define inf 0xffffffff
- #define eps 1e-9
- #define pi acos(-1.0)
- #define P system("pause")
- using namespace std;
- struct point
- {
- double x,y;
- point(double a,double b){x=a;y=b;}
- point (){};
- }p[N],A;
- int n;
- point operator - (point A,point B)
- {
- return point(A.x-B.x,A.y-B.y);
- }
- double dot(point A,point B)
- {
- return A.x*B.x+A.y*B.y;
- }
- double cross(point A,point B)
- {
- return A.x*B.y-A.y*B.x;
- }
- int dcmp(double x)
- {
- if(fabs(x)<eps) return 0;
- if(x<0) return -1;
- return 1;
- }
- int isonsegment(point a1,point a2)
- {
- if((a2.x==A.x&&a2.y==A.y)||(a1.x==A.x&&A.y==a1.y)) return 1;
- return dcmp(cross(a1-A,a2-A))==0&&dcmp(dot(a1-A,a2-A))<0;
- }
- int isonpoly()
- {
-
- int i,wn=0;
- for(i=0;i<n;i++)
- {
- if(isonsegment(p[i],p[(i+n)%n]))
- return 1;
- int k=dcmp(cross(p[(i+1)%n]-p[i],A-p[i]));
- int d1=dcmp(p[i].y-A.y);
- int d2=dcmp(p[(i+1)%n].y-A.y);
- if(k>0&&d1<=0&&d2>0) wn++;
- if(k<0&&d2<=0&&d1>0) wn--;
- }
- if(wn!=0) return 1;
- return 0;
- }
- double length(point B)
- {
- return sqrt(dot(B,B));
- }
- double dist(point a1,point a2 )
- {
- if(a1.x==a2.x&&a1.y==a2.y) return length(A-a1 );
- point v1=a2-a1,v2=A-a1,v3=A-a2;
- if(dcmp(dot(v1,v2)<0)) return length(v2);
- else if(dcmp(dot(v1,v3))>0) return length(v3);
- else return fabs(cross(v1,v2))/length(v1);
- }
-
- int main()
- {
- //freopen("input.txt","r",stdin);
- //freopen("output.txt","w",stdout);
- int m;
-
- while(scanf("%d",&n)&&n)
- {
- int i;
- scanf("%lf%lf",&A.x,&A.y);
- for(i=0;i<n;i++)
- scanf("%lf%lf",&p[i].x,&p[i].y);
- if(isonpoly()){printf("0.00\n");continue;} //判断点是否在多边形上
- double ret=inf;
- for(i=0;i<n;i++)
- ret =min(ret, dist(p[i],p[(i+1)%n]));
- printf("%.2lf\n",ret);
- }
- // P;
- return 0;
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。