当前位置:   article > 正文

hunnu11325(点到多边形的距离)_点到多边形的最短距离acm

点到多边形的最短距离acm

首先判断点是否在多边形上,然后求点到多边形每条边的最短距离

代码如下:

  1. #include<iostream>
  2. #include<algorithm>
  3. #include<string>
  4. #include<stack>
  5. #include<queue>
  6. #include<set>
  7. #include<map>
  8. #include<stdio.h>
  9. #include<stdlib.h>
  10. #include<ctype.h>
  11. #include<time.h>
  12. #include<math.h>
  13. #define N 105
  14. #define inf 0xffffffff
  15. #define eps 1e-9
  16. #define pi acos(-1.0)
  17. #define P system("pause")
  18. using namespace std;
  19. struct point
  20. {
  21. double x,y;
  22. point(double a,double b){x=a;y=b;}
  23. point (){};
  24. }p[N],A;
  25. int n;
  26. point operator - (point A,point B)
  27. {
  28. return point(A.x-B.x,A.y-B.y);
  29. }
  30. double dot(point A,point B)
  31. {
  32. return A.x*B.x+A.y*B.y;
  33. }
  34. double cross(point A,point B)
  35. {
  36. return A.x*B.y-A.y*B.x;
  37. }
  38. int dcmp(double x)
  39. {
  40. if(fabs(x)<eps) return 0;
  41. if(x<0) return -1;
  42. return 1;
  43. }
  44. int isonsegment(point a1,point a2)
  45. {
  46. if((a2.x==A.x&&a2.y==A.y)||(a1.x==A.x&&A.y==a1.y)) return 1;
  47. return dcmp(cross(a1-A,a2-A))==0&&dcmp(dot(a1-A,a2-A))<0;
  48. }
  49. int isonpoly()
  50. {
  51. int i,wn=0;
  52. for(i=0;i<n;i++)
  53. {
  54. if(isonsegment(p[i],p[(i+n)%n]))
  55. return 1;
  56. int k=dcmp(cross(p[(i+1)%n]-p[i],A-p[i]));
  57. int d1=dcmp(p[i].y-A.y);
  58. int d2=dcmp(p[(i+1)%n].y-A.y);
  59. if(k>0&&d1<=0&&d2>0) wn++;
  60. if(k<0&&d2<=0&&d1>0) wn--;
  61. }
  62. if(wn!=0) return 1;
  63. return 0;
  64. }
  65. double length(point B)
  66. {
  67. return sqrt(dot(B,B));
  68. }
  69. double dist(point a1,point a2 )
  70. {
  71. if(a1.x==a2.x&&a1.y==a2.y) return length(A-a1 );
  72. point v1=a2-a1,v2=A-a1,v3=A-a2;
  73. if(dcmp(dot(v1,v2)<0)) return length(v2);
  74. else if(dcmp(dot(v1,v3))>0) return length(v3);
  75. else return fabs(cross(v1,v2))/length(v1);
  76. }
  77. int main()
  78. {
  79. //freopen("input.txt","r",stdin);
  80. //freopen("output.txt","w",stdout);
  81. int m;
  82. while(scanf("%d",&n)&&n)
  83. {
  84. int i;
  85. scanf("%lf%lf",&A.x,&A.y);
  86. for(i=0;i<n;i++)
  87. scanf("%lf%lf",&p[i].x,&p[i].y);
  88. if(isonpoly()){printf("0.00\n");continue;} //判断点是否在多边形上
  89. double ret=inf;
  90. for(i=0;i<n;i++)
  91. ret =min(ret, dist(p[i],p[(i+1)%n]));
  92. printf("%.2lf\n",ret);
  93. }
  94. // P;
  95. return 0;
  96. }


声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/562742
推荐阅读
相关标签
  

闽ICP备14008679号