682. Sum on a segment

 

Given array of integers a1, ..., an. For given indexes l and r find

 

Input. The first line contains the amount of numbers n (1 ≤ n ≤ 106). The second line contains the numbers ai (1 ≤ ai ≤ 1000) space separated. The third line contains the number of queries m (1 ≤ m ≤ 106). Each of the next line contains the query li and ri (1 ≤ lirin).

 

Output. Print in separate m lines the numbers Sli..ri.

 

Sample input

Sample output

5

1 2 3 4 5

5

1 5

2 3

3 4

2 5

1 4

15

5

7

14

10

 

 

 

SOLUTION

partial sums

 

Algorithm analysis

Each query Sl,r can be performed using a loop with a complexity of O(n). We have m ≤ 106 queries and the length of the array is n ≤ 106. If each query runs in linear time, we would need no more than n * m ≤ 1012 operations, which will exceed the Time Limit.

Consider the partial sums of array à:

s1 = a1;

s2 = a1 + a2;

s3 = a1 + a2 + a3;

. . .

sn = a1 + a2 + a3 + . . . + an;

It is possible to compute the values s1, s2, …, sn in a linear array s in O(n) time.

Further note that

Sl,r = al + al + 1 + … + ar =

=  (a1 + … + al + al + 1 + … + ar) – (a1 + … + al-1) = srsl-1

So we can answer the query Sl,r in constant time.

 

Example

Lets compute the sum a3 + a4 + a5 for the input example.

We have: a3 + a4 + a5 = s5s2 = 15 – 3 = 12.

 

Algorithm realization

Declare two working two-dimensional arrays.

 

#define MAX 1000001

int a[MAX], s[MAX];

 

Read the input set of numbers into array a, and calculate the partial sums in array s.

 

scanf("%d",&n); s[0] = 0;

for(i = 1; i <= n; i++)

{

  scanf("%d",&a[i]);

  s[i] = s[i-1] + a[i];

}

 

Process m queries.

 

scanf("%d",&m);

for(i = 0; i < m; i++)

{

  scanf("%d %d",&b,&c);

  printf("%d\n",s[c] - s[b-1]);

}

 

Python realization

Read the input data.

 

n = int(input())

a = [0] + list(map(int, input().split()))

 

Calculate the partial sums of list a in list s.

 

s = [0] * (n + 1)

for i in range(1, n + 1):

  s[i] = s[i - 1] + a[i]

 

Process m queries.

 

m = int(input())

for _ in range(m):

  b, c = map(int, input().split())

  print(s[c] - s[b - 1])