Written By : MathModel
We are asked to answer queries on an integer sequence a=(a_1,a_2,\dots,a_n). For each query (l_i,r_i) let L=l_i,\ R=r_i. We must compute:
i.e. the sum of sums of all non-empty subarrays fully inside .
Claim #1 : For a fixed query , each element a_j contributes independently, by a count equal to the number of subarrays inside that contain position .
Proof : In the expression
the inner sum adds a_j exactly when lies inside the chosen subarray [l,r]. So we can swap the order of summation: instead of summing over subarrays first, we sum over positions , and count how many subarrays include . Thus the total equals
Now we only need to count those subarrays for each .
A subarray [l,r] within contains iff
So:
has (j-L+1) choices.
has (R-j+1) choices.
Therefore the number of subarrays containing is
So the answer for query is:
Claim #2 : The weight (j-L+1)(R-j+1) can be expanded into a quadratic polynomial in .
Proof : Rewrite the weight as:
Expanding:
Thus:
Substitute this back:
So if we can answer the three segment sums
in per query, we are done.
Define prefix sums (1-indexed):
p_0[i]=\sum_{k=1}^i a_k
p_1[i]=\sum_{k=1}^i a_k\cdot k
p_2[i]=\sum_{k=1}^i a_k\cdot k^2
They are precomputed in .
For a query let:
s_0=p_0[R]-p_0[L-1]
s_1=p_1[R]-p_1[L-1]
s_2=p_2[R]-p_2[L-1]
Then:
n,q=map(int,input().split())
a=list(map(int,input().split()))
p=[0]*(n+1)
p2=[0]*(n+1)
p3=[0]*(n+1)
for i in range(n):
p[i+1]=p[i]+a[i]
p2[i+1]=p2[i]+a[i]*(i+1)
p3[i+1]=p3[i]+a[i]*(i+1)*(i+1)
for _ in range(q):
l,r=map(int,input().split())
s0=p[r]-p[l-1]
s1=p2[r]-p2[l-1]
s2=p3[r]-p3[l-1]
ans=-s2+(l+r)*s1+(r+1)*(1-l)*s0
print(ans)Complexity: \mathcal{O}(n+q)