hdu 3400Line belt 经典 三分

来源:互联网 发布:java 遍历 list 编辑:程序博客网 时间:2024/06/05 10:29

原文地址  点击打开链接




题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=3400

题目大意:在平面上有两条直线:AB,CD,从A到D,如果在直线AB上行驶有速度P,在直线CD上行驶有速度Q,其它地方有速度R,求A到D的最短花费时间。

解题思路:

              首先固定AB上一点,第一次我们设把这点设为mid1=B,然后三分去CD上找一点mid2,使A到D花的时间最少。然后固定CD上的mid2,用三分法去AB上找一点mid1,使A->mid1->mid2->D,花费时间最少,重复上述过程。

代码:

[cpp] view plaincopy
  1. #include<iostream>  
  2. #include<cmath>  
  3. using namespace std;  
  4. const double eps=1e-8;  
  5. struct point  
  6. {  
  7.     double x;  
  8.     double y;  
  9. };  
  10. point A,B,C,D;  
  11. double P,Q,R;   
  12. point Mid(point l, point r)  
  13. {  
  14.     point mid;  
  15.     mid.x=(l.x+r.x)/2.0;  
  16.     mid.y=(l.y+r.y)/2.0;  
  17.     return mid;  
  18. }  
  19. double detance(point a,point b)  
  20. {  
  21.     return sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y));  
  22. }  
  23.   
  24. double stime(point a,point b,point c,point d)  
  25. {  
  26.     return detance(a,b)/P+detance(b,c)/R+detance(c,d)/Q;  
  27. }  
  28. double sanfen1(point a, point b, point c, point d,point &mid)  
  29. {  
  30.     double rest1,rest2;  
  31.     point l,r,mid1,mid2;  
  32.     l=c;  
  33.     r=d;  
  34.     do  
  35.     {  
  36.         mid1=Mid(l,r);  
  37.         mid2=Mid(mid1,r);  
  38.         rest1=stime(a,b,mid1,d);  
  39.         rest2=stime(a,b,mid2,d);  
  40.         if(rest1>rest2)l=mid1;  
  41.         else r=mid2;  
  42.     }while(fabs(rest1-rest2)>eps);  
  43.     mid=mid1;  
  44.     return rest1;  
  45. }  
  46. double sanfen2(point d, point c, point b, point a,point &mid)  
  47. {  
  48.     double rest1,rest2;  
  49.     point l,r,mid1,mid2;  
  50.     l=a;  
  51.     r=b;  
  52.     do  
  53.     {  
  54.         mid1=Mid(l,r);  
  55.         mid2=Mid(mid1,r);  
  56.         rest1=stime(a,mid1,c,d);  
  57.         rest2=stime(a,mid2,c,d);  
  58.         if(rest1>rest2)l=mid1;  
  59.         else r=mid2;  
  60.     }while(fabs(rest1-rest2)>eps);  
  61.     mid=mid1;  
  62.     return rest1;  
  63. }  
  64. int main()  
  65. {  
  66.     int t;  
  67.   
  68.     scanf("%d",&t);  
  69.     while(t--)  
  70.     {  
  71.         scanf("%lf%lf%lf%lf",&A.x,&A.y,&B.x,&B.y);  
  72.         scanf("%lf%lf%lf%lf",&C.x,&C.y,&D.x,&D.y);  
  73.         scanf("%lf%lf%lf",&P,&Q,&R);  
  74.         double  t1,t2;  
  75.         point mid1,mid2;  
  76.         mid1.x=B.x;  
  77.         mid1.y=B.y;  
  78.         do  
  79.         {  
  80.             t1=sanfen1(A,mid1,C,D,mid2);  
  81.             t2=sanfen2(D,mid2,B,A,mid1);  
  82.         }while(fabs(t1-t2)>eps);  
  83.         printf("%0.2lf/n",t1);  
  84.   
  85.     }  
  86.     return 0;  
  87. }