CP: Range sum queries

Answer q questions about an array: what is the sum of a[l..r]? Positions are numbered from 1. Use prefix sums, so each question takes O(1).

Input

The first line has n and q (1 ≤ n, q ≤ 10,000). The second line has the n numbers (each from -10⁹ to 10⁹). Each of the next q lines has l and r (1 ≤ l ≤ r ≤ n).

Output

One line per question: the sum.

Examples

Example 1 · Input
6 3
3 1 4 1 5 9
1 3
3 6
5 5
Expected output
8
19
5
Example 2 · Input
1 1
-7
1 1
Expected output
-7

Hints

Hint 1

Build pre with n + 1 cells: pre[i + 1] = pre[i] + a[i].

Hint 2

With 1-based l and r, the sum is pre[r] - pre[l - 1].

Hint 3

Use long long: sums reach 10^13.

Solution

Show one correct solution (try it yourself first)
#include <iostream>
#include <vector>
using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int n, q;
    cin >> n >> q;
    vector<long long> pre(n + 1, 0);
    for (int i = 0; i < n; i++) {
        long long x;
        cin >> x;
        pre[i + 1] = pre[i] + x;
    }
    for (int i = 0; i < q; i++) {
        int l, r;
        cin >> l >> r;
        cout << pre[r] - pre[l - 1] << "\n";
    }
    return 0;
}

Lesson: Prefix sums →