Official

F - Cumulative Cumulative Cumulative Sum Editorial by en_translator


First, let us consider how many times \(A_i (i\leq x)\) contributes to \(D_x\).

For each \(x\), \(A_i\) contributes to \(B_x\) once.
For each \(x\), \(A_i\) contributes to \(C_x\) \((x-i+1)\) times.
For each \(x\), \(A_i\) contributes to \(D_x\) \(\left( (x-i+1)(x-i+2)/2 \right)\) times.

Therefore, we have \(\displaystyle D_x=\sum_{i=1}^{x}\frac{(x-i+1)(x-i+2)}{2}A_i\), which can be transformed into

\(\displaystyle D_x=\frac{1}{2}\sum_{i=1}^{x}i^2A_i - \frac{2x+3}{2}\sum_{i=1}^{x}iA_i+\frac{(x+1)(x+2)}{2}\sum_{i=1}^{x}A_i.\)

With a data structure that enables updating \(i^2A_i,iA_i\), and \(A_i\), and obtaining the prefix sum, like a Fenwick tree or a segment tree, each query can be processed in an \(O(\log N)\) time.

Sample code (C++)

posted:
last update: