三分查找,汽车转弯

来源:互联网 发布:带网络功能的pe系统 编辑:程序博客网 时间:2024/04/29 17:27

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>

Input
Every line has four real numbers, x, y, l and w.<br>Proceed to the end of file.<br>

Output
If he can go across the corner, print "yes". Print "no" otherwise.<br>

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

Sample Output
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");


    }






}
0 0