当前位置:Gxlcms > mysql > URAL1348.GoatintheGarden2[求点到线段的距离]

URAL1348.GoatintheGarden2[求点到线段的距离]

时间:2021-07-01 10:21:17 帮助过:18人阅读

题目链接:http://acm.timus.ru/problem.aspx?space=1num=1348 题目的意思是:求一个点到线段的最短距离和最长距离。。 最长距离比较容易,就是求点到线段两个端点较长的那个距离就是ans。 最短距离就比较有意思了。。。 可能的情况就是点到线段的垂线的垂足

题目链接:http://acm.timus.ru/problem.aspx?space=1&num=1348

题目的意思是:求一个点到线段的最短距离和最长距离。。

最长距离比较容易,就是求点到线段两个端点较长的那个距离就是ans。

最短距离就比较有意思了。。。

可能的情况就是点到线段的垂线的垂足在线段内,还有就是垂足在线段外。。。

在线段内的话,那么应用叉积求面积+底面长度可以求得垂线长度也就是最短距离。。

如果在线段外的话,最短距离就是点到线段的两个端点的最小值。。

那么问题就来了。。怎么判断垂足在线段内还是在线段外的呢??

详细见代码。 - - 。。。

Code:

  1. #include <iostream>
  2. #include
  3. #include <cstdio>
  4. #include <cstring>
  5. #include <cmath>
  6. using namespace std;
  7. const double eps = 1e-8;
  8. const double pi = acos(-1);
  9. //点
  10. struct POINT
  11. {
  12. double x, y;
  13. POINT(){ }
  14. POINT(double a, double b){
  15. x = a;
  16. y = b;
  17. }
  18. };
  19. //线段
  20. struct Seg
  21. {
  22. POINT a, b;
  23. Seg() { }
  24. Seg(POINT x, POINT y){
  25. a = x;
  26. b = y;
  27. }
  28. };
  29. //直线
  30. struct Line
  31. {
  32. POINT a, b;
  33. Line() {}
  34. Line(POINT x, POINT y){
  35. a = x;
  36. b = y;
  37. }
  38. };
  39. //叉乘
  40. double cross(POINT o, POINT a, POINT b)
  41. {
  42. return (a.x - o.x) * (b.y - o.y) - (b.x - o.x) * (a.y - o.y);
  43. }
  44. //求两点间的距离
  45. double dis(POINT a, POINT b)
  46. {
  47. return sqrt((a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y));
  48. }
  49. Seg s;
  50. POINT p;
  51. double L;
  52. //点到直线的距离..
  53. double PointToLine(POINT p, Line l)
  54. {
  55. return fabs(cross(p, l.a, l.b)) / dis(l.a, l.b);
  56. }
  57. //线段到直线的距离..
  58. double PointToSeg(POINT p, Seg s)
  59. {
  60. POINT tmp = p;
  61. tmp.x += s.a.y - s.b.y;
  62. tmp.y += s.b.x - s.a.x;
  63. if(cross(s.a, p, tmp) * cross(s.b, p, tmp) >= 0){
  64. return min(dis(p, s.a), dis(p, s.b));
  65. }
  66. return PointToLine(p, Line(s.a, s.b));
  67. }
  68. void solve()
  69. {
  70. double ans1 = PointToSeg(p, s), ans2 = max(dis(p, s.a), dis(p, s.b));
  71. printf("%.2lf\n%.2lf\n", ans1 > L ? ans1 - L : 0, ans2 > L ? ans2 - L : 0);
  72. return ;
  73. }
  74. int main()
  75. {
  76. // freopen("11.txt", "r", stdin);
  77. while(~scanf("%lf %lf %lf %lf", &s.a.x, &s.a.y, &s.b.x, &s.b.y)){
  78. scanf("%lf %lf %lf", &p.x, &p.y, &L);
  79. solve();
  80. }
  81. return 0;
  82. }</cmath></cstring></cstdio></iostream>

--->

好吧,还需要好好的学习。。。

人气教程排行