B - Light Bulb (三分)

Compared to wildleopard’s wealthiness, his brother mildleopard is rather poor. His house is narrow and he has only one light bulb in his house. Every night, he is wandering in his incommodious house, thinking of how to earn more money. One day, he found that the length of his shadow was changing from time to time while walking between the light bulb and the wall of his house. A sudden thought ran through his mind and he wanted to know the maximum length of his shadow.

图片:https://odzkskevi.qnssl.com/e08f9b87bb202cc3c5724ca803044b84?v=1531709449

Input
The first line of the input contains an integer T (T <= 100), indicating the number of cases.

Each test case contains three real numbers H, h and D in one line. H is the height of the light bulb while h is the height of mildleopard. D is distance between the light bulb and the wall. All numbers are in range from 10-2 to 103, both inclusive, and H - h >= 10-2.

Output
For each test case, output the maximum length of mildleopard’s shadow in one line, accurate up to three decimal places..

Sample Input
3
2 1 0.5
2 0.5 3
4 3 4

Sample Output
1.000
0.750
4.000

三分法:

如果一个函数f 在区间[l,r]上只有一个波峰,求其极值,可用三分。

mid=(l+r)/2;
midmid=(mid+r)/2;
如果 y(mid) 大于 y(midmid) 则 r=midmid,反之l=mid;(求最大值)

Code:

设人与灯之间的距离是x,人的投在竖着的墙上的影子长度为k,那么由三角形相似可知
x/D-x=H-h/k
影子总长度为:L=D-x+k
r=D,
l=D-h×D/H
即人的影子都投不到墙上的时候

#include <iostream>
#include<cstdio>
#define ll long long
using namespace std;
double H,h,d,ep;
double ans(double x)
{
    return H-(H-h)*d/x+d-x;
}
int main()
{
    int t;
    cin>>t;
    ep=1e-10;
    while(t--)
    {
        double l,r;
        cin>>H>>h>>d;
        l=d-h*d/H;
        r=d;
        double mid,mmid;
        while(l+ep<r)
        {
            mid=(l+r)/2.0;
            mmid=(mid+r)/2.0;
            if(ans(mid)>ans(mmid))
                r=mmid;
            else
                l=mid;

        }
        double sum=ans(l);
        printf("%.3lf\n",sum);



    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41700151/article/details/81100505