PROBLEM LINK:
Practice
Contest: Division 1
Contest: Division 2
Contest: Division 3
Contest: Division 4
Author: iceknight1093
Tester: raysh07
Editorialist: iceknight1093
DIFFICULTY:
Simple
PREREQUISITES:
None
PROBLEM:
There are two alarms, one that rings at X, 2X, 3X, \ldots and the other at Y, 2Y, 3Y, \ldots
Find the smallest time t such that:
- One alarm rings at t
- The other alarm rings at s \le t
- t-s \le D
EXPLANATION:
The first alarm rings at times X, 2X, 3X, \ldots
Let’s look at when it rings at time A\cdot X, for some integer A\gt 0.
What’s the nearest time the other alarm rings?
Well, the second alarm must ring at some time of the form B\cdot Y.
In particular, the nearest ring to A\cdot X, that doesn’t exceed it, is given by choosing
We can compute this B_1 in constant time, and check if the resulting distance is \le D or not.
If it is, update the answer with AX.
Note now that B_1 + 1 gives the next ring of the second alarm; so we can also compute that and check if its distance to AX is \le D; and if it is, update the answer with (B_1 + 1)\cdot Y.
So, if we fix the value of A, we can easily check if the ring at AX of the first alarm will result in a wakeup.
However, how do we decide which values of A to check?
Luckily, we don’t need to check too many of them!
Observe that at XY, both alarms will ring.
So, we only really need to check for 1 \le A \le Y.
Since the sum of Y across all tests is bounded by 10^6, this is fast enough.
Bonus: Solve the problem for higher constraints, as in X, Y \le 10^{18}.
TIME COMPLEXITY:
\mathcal{O}(Y) per testcase.
CODE:
Editorialist's code (PyPy3)
for _ in range(int(input())):
x, y, d = map(int, input().split())
ans = x*y
for a in range(1, y+1):
b = (a*x) // y
if a*x - b*y <= d: ans = min(ans, a*x)
if (b+1)*y - a*x <= d: ans = min(ans, (b+1)*y)
print(ans)