Optional: different kinds of totals
Use numeric helpers correctly and derive weighted or modular prefix formulas.
Library helpers still have numeric types
<numeric> provides std::partial_sum for running totals, std::adjacent_difference for consecutive differences, and std::accumulate for one final total. Allocate output entries before writing; reserve alone changes capacity, not vector size.
partial_sum accumulates using the input iterator’s value type. A vector<long long> destination does not make vector<int> input accumulation wide. Use long long input or an explicit wide loop. For accumulate, the initial value controls the accumulator type: use 0LL for long long. These helpers do not record interval-update markers for you.
Shift global weights to local weights
For a query a[l] + 2a[l + 1] + ... + (r − l + 1)a[r], store ordinary prefixes P and globally weighted prefixes W[i] = sum of j × a[j] through i. The desired relative weight at position i is i − l + 1.
Therefore answer = (W[r] − W[l − 1]) − (l − 1)(P[r] − P[l − 1]). Build in O(n), answer in O(1), and allocate O(n). The source’s |a[i]| ≤ 10⁶ bound keeps the weighted totals and intermediate products within long long.
// Complete C++23 program. Input: n q, n values, q inclusive ranges.
// n,q <= 200000; |value| <= 1e6.
#include <iostream>
#include <vector>
int main() {
int n, q;
std::cin >> n >> q;
std::vector<long long> pref(n + 1, 0), weighted(n + 1, 0);
for (int i = 1; i <= n; ++i) {
long long value;
std::cin >> value;
pref[i] = pref[i - 1] + value;
weighted[i] = weighted[i - 1] + i * value;
}
while (q--) {
int l, r;
std::cin >> l >> r;
long long sum = pref[r] - pref[l - 1];
long long global = weighted[r] - weighted[l - 1];
std::cout << global - (l - 1LL) * sum << '\n';
}
}Normalize modular differences
For positive modulus M, normalize each signed input with (value % M + M) % M and keep prefixes in [0, M). Then a range’s nonnegative residue is (P[r] − P[l − 1] + M) % M. C++ remainder can be negative, so the normalization matters.
M must not be zero. When M = 1, every answer is zero. Reducing modulo M does not repair overflow in a multiplication performed before the remainder operation; check intermediate bounds as well as stored residues.
Why can partial_sum from vector<int> into vector<long long> still overflow?
Turn the idea into code
For [4, −2, 7, 0, 3], calculate the relative-weighted sum of [2,5]. Also normalize the integer −1 modulo 5.
Give me a hint
The first value in the queried range must have weight 1, not its global index.
Show the explained solution
The weighted answer is 1×(−2) + 2×7 + 3×0 + 4×3 = 24. The normalized residue of −1 modulo 5 is 4. A global weighted prefix needs the (l − 1) correction to produce these local weights.
Your notes
Mark complete when you can explain it yourself.