PHƯỚC HƯNG OJ · THỬ THÁCH THUẬT TOÁN

#PS0000275. Tổng các tổng đoạn (Sums of Segments)

HỌC THEO LỘ TRÌNH

Bài tập thuộc lộ trình

1 lộ trình

Tổng các tổng đoạn (Sums of Segments)

Sums of Segments

Source: Codeforces

Version: Phuoc Hung OJ Extended

Problem Statement

Given an integer array a1,…,ana_1,\ldots,a_n, define s(l,r)=∑i=lrais(l,r)=\sum_{i=l}^{r}a_i. Form bb by listing, for each start l=1,2,…,nl=1,2,\ldots,n, the values s(l,l),s(l,l+1),…,s(l,n)s(l,l),s(l,l+1),\ldots,s(l,n) in that order. Its length is n(n+1)/2n(n+1)/2. For example, a=(1,2,5,10)a=(1,2,5,10) yields b=(1,3,8,18,2,7,17,5,15,10)b=(1,3,8,18,2,7,17,5,15,10). For each query (L,R)(L,R), compute ∑j=LRbj\sum_{j=L}^{R}b_j. Both arrays use 1-based indexing.

Input

Line 1 contains nn. Line 2 contains nn integers aia_i. Line 3 contains qq. Each of the next qq lines contains L,RL,R.

Output

Print one answer per line, in query order.

Subtasks

  • Subtask 1 (20 points): 1≤n≤301\le n\le30; 1≤q≤401\le q\le40; ∣ai∣≤10|a_i|\le10; 1≤l≤r≤n(n+1)/21\le l\le r\le n(n+1)/2.
  • Subtask 2 (30 points): 1≤n≤3000001\le n\le300000; 1≤q≤3000001\le q\le300000; ∣ai∣≤10|a_i|\le10; 1≤l≤r≤n(n+1)/21\le l\le r\le n(n+1)/2; l=rl=r for every query.
  • Subtask 3 (50 points): 1≤n≤3000001\le n\le300000; 1≤q≤3000001\le q\le300000; ∣ai∣≤10|a_i|\le10; 1≤l≤r≤n(n+1)/21\le l\le r\le n(n+1)/2.

Example 1

Input

4
1 2 5 10
15
1 1
1 2
1 3
1 4
1 5
1 10
5 10
6 10
2 8
3 4
3 10
3 8
5 6
5 5
1 8

Output

1
4
12
30
32
86
56
54
60
26
82
57
9
2
61

Explanation

The array b is (1,3,8,18,2,7,17,5,15,10). Query (2,8) sums 3+8+18+2+7+17+5=60; (5,6) sums 2+7=9. The other queries are evaluated in the same way.

Example 2

Input

3
-2 3 -1
3
1 6
2 4
6 6

Output

3
4
-1

Explanation

The array is (-2,1,0,3,2,-1). The total is 3; the second query gives 1+0+3=4; the last gives -1.