Let be the distance from the starting point to the target. Walking directly takes time. A jump always covers exactly distance, takes time , and may be made in any direction; walking can cover any remaining distance.
Write and , so . The natural candidates are:
- Walk all the way: .
- Make jumps toward the target, then walk the remaining : .
- Make jumps in the target direction and walk back the overshoot : .
- Reach the target using jumps: . For , make jumps along the target direction, then use two jumps whose resultant displacement is . Any resultant length from to is possible with two length- jumps, and . For , two jumps can directly have resultant length , so the same time applies.
These candidates cover the optimum. With jumps, the remaining distance cannot be less than , so that strategy costs at least , a linear function of whose minimum on this range occurs at or . With at least jumps, the jump cost alone is at least , and that cost is achievable as described above. This also handles ; for one jump, the best remaining distance is , and two jumps can reach the target. Thus the minimum of the listed candidates is valid, including when or .
C++17 implementation
hypot computes the Euclidean distance robustly. The running time and extra space are both .
#include <algorithm>
#include <cmath>
#include <iomanip>
#include <iostream>
int main() {
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
double x, y, jumpDistance, jumpTime;
std::cin >> x >> y >> jumpDistance >> jumpTime;
const double distance = std::hypot(x, y);
const auto q = static_cast<long long>(std::floor(distance / jumpDistance));
const double remainder = distance - q * jumpDistance;
double answer = distance;
if (q == 0) {
answer = std::min({answer,
jumpTime + jumpDistance - distance,
2.0 * jumpTime});
} else {
answer = std::min({answer,
q * jumpTime + remainder,
(q + 1) * jumpTime + jumpDistance - remainder,
(q + 1) * jumpTime});
}
std::cout << std::fixed << std::setprecision(10) << answer << '\n';
return 0;
}