Source Code
#include "bits/stdc++.h"

using namespace std;
typedef long long ll;

const int MOD = 1e9 + 7;
inline int add(ll a, ll b) { return a + b >= MOD ? a + b - MOD : a + b; }
inline int mul(ll a, ll b) { return (ll)a * b % MOD; }
inline int sub(ll a, ll b) { return a - b < 0 ? a - b + MOD : a - b; }
inline int Sum(ll a) { return (a * (a + 1) / 2) % MOD;  }

int main() {
    ios_base::sync_with_stdio(0);
    cin.tie();
    ll l, r, x, y, k;
    cin >> l >> r >> x >> y >> k;

    ll dif = r - l + 1;
    ll sum = add(mul(l - 1, dif), Sum(dif));
    ll total_cost = mul(sum, x);

    ll breaks = 0;
    ll first = ll(l) + k - (l % k == 0 ? k : l % k);
    ll last = ll(r) - r % k;

    if(first > last) {
        breaks = mul(r - l + 1, l / k);
        breaks = mul(breaks, y);
        cout << add(total_cost, breaks);
        return 0;
    }

    ll num_of_sets = (last - first) / k;
    breaks = add(mul((first - 1) / k, num_of_sets), Sum(num_of_sets));
    breaks = mul(breaks, k);

    ll fromLeftToFirst = mul(first - l + 1, l / k - (l == first));
    ll fromLastToright = mul(r - last, r / k);
    breaks = add(breaks, fromLeftToFirst);
    breaks = add(breaks, fromLastToright);

    ll breaks_cost = mul(breaks, y);
    total_cost = add(total_cost, breaks_cost);

    cout << total_cost << '\n';
}
Copy
Practice Practice OsamaX01
GNU G++17
1 ms
748 KB
Accepted