D - Freefall Editorial by spheniscine


Let \(\displaystyle f(x) = \small\frac A {\sqrt{x+1}} + Bx\), i.e. the total time taken if Takahashi uses his power \(x\) times. (Note we only care about integer values of \(x\), though the result might not be an integer.) If you graph this function for various positive values of \(A\) and \(B\), you’ll note it is unimodal, i.e. there is a minimum point \(f(k)\) for some \(k\), and the function never decreases on either side of \(k\) moving away from \(k\). (This can be proven by analyzing the function’s derivative, which is beyond the scope of this editorial.)

One might be tempted to use binary search (a sensible upper bound is \(\displaystyle \small\frac A B\), as you could verify that \(\displaystyle f(0) \leq f ( \small\frac A B ) \leq 2A\)) to compare \(f(x)\) and \(f(x+1)\), and it’d theoretically be correct as the function is also a convex function; however, if you are using 64-bit floating points (e.g. C++ double), you may get an incorrect answer. This is because floating points don’t have enough precision to represent all the integers to \(10^{18}\) exactly, so you may get \(x = x+1 \Rarr f(x) = f( x+1)\) when the truly correct comparison is \(f(x) > f(x+1)\).

A more reliable method is to use ternary search. Note that since the input to the function should be integers rather than floats, instead of terminating when the range is under a small error limit, simply brute-force the remaining values when \(r - l < 3\).

posted:
last update: