PROBLEM LINK:
Author: Hasan Jaddouh
Tester: Misha Chorniy
Editorialist: Pushkar Mishra
DIFFICULTY:
Easy
PREREQUISITES:
Binary search
PROBLEM:
Given two numbers H and S, find a right triangle such that the hypotenuse is of length H and its area is S. If no such triangle exists, output -1.
EXPLANATION:
A right triangle with a fixed hypotenuse H has a very nice property related to areas: the maximum area will be when the triangle is isosceles, i.e., base B and perpendicular P are equal. This implies that the maximum area will be when B=P=\sqrt{\frac{H^2}{2}} (follows from the pythagorus theorem P^2 + B^2 = H^2).
Let us only talk in terms of the base B. So, when B = \sqrt{\frac{H^2}{2}}, then the area is maximised. For all other bases from 0 up to this limit, the area monotonically increases. Also, beyond this limit, area monotonically decreases.
That is the main hint: MONOTONICITY! We can binary search on the base B between the limits 0 and \sqrt{\frac{H^2}{2}} because beyond this value, the behavior is symmetric. By binary searching on the base, we mean that we try bases such that we can reach our target area.
While binary searching, we have to take care of the fact that we remain in the error bound. Since we want the error in our answers to be less than 0.01, it would be best that we do a binary search such that the area of the resultant triangle with the given base has error less than 10^{-8} when compared with given area S. This is because only then, the absolute error in side will be less than 0.01 (this follows from the fact that we are using square root to calculate the other side and also that area is the product of the sides).
Please see editorialist’s/setter’s program for implementing binary search with that precision.
COMPLEXITY:
\mathcal{O}(\log N) per test case.