Module: Prefix sums


Problem

1 /8


The amount on the line

Theory Click to read/hide

Let there be some array. In the absence of changes, we can quickly (faster than a line) find the value of some functions on a subsegment of this array. To do this, we need to use additional memory and do a pre-calculation.
For example, we need to quickly find the sum on some segment of the array.
Let's get an array of prefix sums, in which the index i will be the sum of all elements of the array with indices less than or equal to i.
a[] – given array, p[] – array of prefix sums


Array count p:
Obviously p[0] = a[0]. Note that we can easily recalculate p[i] via p[i – 1], because the amount on the i prefix is ​​the amount on the i prefix – 1 + a[i].
Thus, the code for calculating prefix sums looks like this:

int a[n], p[n];
p[0] = a[0< /span>];
for (int i = 1; i < n; i++)
         p[i] = p[i -  1] + a[i];

Further, we note that the sum on the segment – the difference between the two sums on the prefix.


Green = red – blue
Thus, if it is necessary to find the sum on the interval [l,r], then the answer is p[r] – p[l-1].
However, if l – 1 element may not exist. In order to do without if’s, you can enter 1-indexing, and a[0] and p[0] will have neutral values ​​(0 for the sum).
 
Note that this technique is a special case of the inclusion-exclusion formula, so in this way it is possible to store not only sums, but also other functions, such as multiplication and xor.
 

Problem

Given an immutable array of length n and q queries like “calculate the sum of an array subsegment from l to r ”. Print the answer for each request.

Input
The first line contains a number n – array size (\(1 <= n <= 10^5\)). The second line contains n &ndash numbers ; array elements. Modulo numbers do not exceed \(10^9\). The third line contains the number q – number of requests (\(1 <= q <= 10^5\)). Followed by q lines, each of which contains 2 numbers: l and r (\(1 <= l <= r <= n\)).

Output
Print the answers to all queries, each on a separate line.
 

 

Examples
# Input Output
1
5
1 2 3 4 5
3
1 2
3 3
2 5
3
3
14