您的位置:首页 > 其它

三分查找,汽车转弯

2016-04-17 21:10 190 查看
Mr. West bought a new car! So he is travelling around the city.<br><br>One day he comes to a vertical corner. The street he is currently in has a width x, the street he wants to turn to has a width y. The car has a length l and a
width d.<br><br>Can Mr. West go across the corner?<br><img src=../../../data/images/2438-1.jpg><br>

[align=left]Input[/align]
Every line has four real numbers, x, y, l and w.<br>Proceed to the end of file.<br>

[align=left]Output[/align]
If he can go across the corner, print "yes". Print "no" otherwise.<br>

[align=left]Sample Input[/align]

10 6 13.5 4<br>10 6 14.5 4<br>

[align=left]Sample Output[/align]

yes<br>no<br>

如下图



本次的变量是α角,函数为h,h是先增大后减小的。

根据三分查找遍的:

#include<iostream>

#include<stdio.h>

#include<cmath>

using namespace std;

double pi = acos(-1.0);//α角为180度

double s,h,x,y,l,w;//用于函数全局变量

double f(double p)//函数

{

    s = l*cos(p) + w*sin(p) - x;

    h = s*tan(p) + w*cos(p);

    return h;

}

int main()

{

    double left,right,mid,midmid;

    while(scanf("%lf%lf%lf%lf",&x,&y,&l,&w)!=EOF)

    {

         left = 0.0;

         right = pi/2;

      while(fabs(right-left)>1e-8)//三分查找的终止条件,left与right的无限接近

      {

        mid = (left + right)/2;

        midmid = (mid + right)/2;

        if(f(mid) >= f(midmid))

            right = midmid;

        else

            left = mid;

      }

      if(f(mid) <= y)

        printf("yes\n");

      else

        printf("no\n");

    }

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: