B - Garbage Collection Editorial by evima

Another Solution

Consider a scenario where a type of garbage, which is collected on days where the date modulo \(q\) equals \(r\), is put out on day \(d\).

Consider how many days after day \(d\) the garbage will be collected, and this number of days corresponds to \((r - d) \bmod q\). Here, the modulo operation yields a non-negative result even if \(r - d\) is negative. (For example, \(-9 \bmod 7 = 5\).) Therefore, the answer is \(d + (r - d) \bmod q\).

By using a for loop to perform this calculation \(Q\) times, the original problem can be solved. In languages like C++, be cautious with the modulo operation. (You may need to use (a % b + b) % b instead of just a % b.)

Sample Implementation (Python):

N = int(input())
q, r = [0] * N, [0] * N
for i in range(N):
    q[i], r[i] = map(int, input().split())
Q = int(input())
for _ in range(Q):
    t, d = map(int, input().split())
    print(d + (r[t - 1] - d) % q[t - 1])

posted:
last update: