Problem 212
Range Sum Queries
Easy · 10 pts · Array, Prefix Sum
Problem
You are given an array of N integers and Q queries. Each query gives two indices L and R (zero-based) and asks for the sum of the elements from index L to index R, inclusive. Print the answer to each query on its own line. Adding up each range separately can take O(N) per query, too slow for 100,000 queries. Precompute prefix sums once, with P[0] = 0 and P[i + 1] = P[i] + A[i]; then the sum from L to R is P[R + 1] - P[L], available in O(1).
Input
First line: integer N. Second line: N integers. Third line: integer Q. Next Q lines: L and R.
Output
Print the answer to each query on its own line.
Constraints
1 <= N, Q <= 100000; -100000 <= A[i] <= 100000; 0 <= L <= R < N
Example input
5 1 3 5 7 9 2 1 3 0 4
Example output
15 25
Explanation
The array is 1 3 5 7 9. The first query, 1 3, covers 3 + 5 + 7 = 15. The second, 0 4, covers the whole array: 1 + 3 + 5 + 7 + 9 = 25.