Official

B - Garbage Collection Editorial by en_translator


The date whose remainder divided by \(q\) is \(r\) is represented as day \((aq+r)\) for some non-negative integer \(a\). Thus, it is sufficient to find the minimum \(a\) with \(d \leq aq + r\).

Let \(b\) and \(c\) be the quotient and remainder when \(d\) is divided by \(q\), respectively. Then, \(d=bq + c\). Now compare \(c\) and \(r\).

If \(c \leq r\), the minimum \(a\) with \(d \leq aq + r\) is \(a=b\), so the answer is \(bq+r\).

If \(c > r\), the minimum \(a\) with \(d \leq aq + r\) is \(a=b+1\), so the answer is \((b+1)q+r\).

Sample code

N = int(input())
q = [0] * N
r = [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())
    t -= 1
    b, c = divmod(d, q[t])
    a = b if c <= r[t] else b + 1
    ans = a * q[t] + r[t]
    print(ans)

Sample code (C++)

#include <bits/stdc++.h>
using namespace std;

int main() {
    int N;
    cin >> N;
    vector<int> q(N), r(N);
    for (int i = 0; i < N; ++i) cin >> q[i] >> r[i];
    int Q;
    cin >> Q;
    while (Q--) {
        int t, d;
        cin >> t >> d;
        --t;
        int b = d / q[t], c = d % q[t];
        int a = c <= r[t] ? b : b + 1;
        int ans = a * q[t] + r[t];
        cout << ans << "\n";
    }
}

posted:
last update: