Official

B - Christmas Trees Editorial by en_translator


First, let us simplify the problem by subtracting \(A\) from \(L\) and \(R\), so that Christmas trees are standing at the points whose coordinates are multiples of \(M\).

Let \(k\) be the index of the tree standing at the coordinate \(kM\). Let \(l\) be the index of the eastmost tree standing at a coordinate strictly less than \(L\) and \(r\) be that at a coordinate less than or equal to \(R\). Then the answer is \(r-l\).

All that left is to find the index of the eastmost tree standing at a coordinate less than or equal to \(x\), for some \(x\); this is simply represented as \(\lfloor \frac{x}{M} \rfloor\). Note that when \(x\) is negative, the way to find \(\lfloor \frac{x}{M} \rfloor\) varies depending on your programming language. (For example in C++, you cannot simply write x / M.) Also, the approach of evaluating \(\frac{x}{M}\) on floating point numbers to obtain a real number then flooring it may not result in a wrong value because of a precision error, so be careful.

Sample code (C++):

#include<bits/stdc++.h>

using namespace std;

using ll = long long;

ll floor(ll x, ll m) {
    ll r = (x % m + m) % m;
    return (x - r) / m;
}

int main() {
    ll a, m, l, r;
    cin >> a >> m >> l >> r;
    l -= a, r -= a;
    cout << floor(r, m) - floor(l - 1, m) << endl;
}

Sample code (Python) :

a, m, l, r = map(int, input().split())
l -= a
r -= a
print(r // m - (l - 1) // m)

posted:
last update: