Can someone help me out in this question

can someone help me out in this question

Let’s call the answer l. Now, If you see, as l increases, h decreases. Let’s calculate the value of h for some given l.
We start with writing the lines in co-ordinate form, let us assume the start of the bottom line is (0,0).
The first line passes through (0,0) and (l, \sqrt{a^2 - l^2}) by pythagoras
theorem.The second line passes through the points (0, \sqrt{b^2 - l^2}) and (l,0).
We can now find their equations.
Line 1 : y = x\sqrt{a^2 - l^2}/l
Line 2 : y = (l-x)\sqrt{b^2 - l ^2}/l
Removing x using the 2 equations, gives us
y = \sqrt{a^2 - l^2}\sqrt{b^2 - l^2}/(\sqrt{a^2 - l^2} + \sqrt{b^2 - l^2}).
The y co-ordinate of their intersection is h.
Now we binary search over l. If y is too small, then we decrease l, else we increase it.
One important thing to note, is that if h>ab/(a+b), then there is no solution because that’s the answer for l=0, and since l can’t be negative, and the answer is largest at 0, so h would be larger than the largest possible value.

My code
#include <iostream>
#include <bits/stdc++.h>
#include <cmath>
#include <vector>
#define ll long long int
#define mp make_pair
#define pb push_back
#define vi vector<int>
using namespace std;
long double a,b,h;
const long double eps=1e-5;
long double calc(long double l){
    long double x=sqrtl(b*b - l*l); 
    long double y=sqrtl(a*a - l*l);
    return (x*y)/(x+y);
}
void solve(){
    cin>>a>>b>>h;
    long double mn=0;
    long double mx=min(a,b);
    long double l=(mn + mx)/2;
    if(h > (a*b)/(a+b)){
        cout<<"-1\n";
        return;
    }
    while(mx-mn > eps/10){
        if(calc(l)>h){
            mn=l;
            l = (l+mx)/2;
        } 
        else{
            mx=l;
            l=(l+mn)/2;
        }
    }
    cout<<fixed<<setprecision(9)<<(mn+mx)/2<<"\n";
}
int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    int t;
    cin >>t;
    while(t--){
        solve();
    }
}
1 Like