Editorial for RGPC '17 P2 - Cubes are Life
Submitting an official solution before solving the problem yourself is a bannable offence.
Author:
To keep track of cubes and their values, use an array , where the index represents the value of the cube and the element represents the position of the cube in the original line (i.e.
means that the cube with value
is at position
). Notice that for each query, if you were to iterate from position
to position
, adding each value to a counter, you would run out of time due to the large number of cubes and queries (time complexity
).
Instead, use a prefix sum array data structure , where
equals the sum of all values from cube
to cube
. Therefore, the sum of all values from cubes
to
can be expressed as
. Proof is left as an exercise for the reader. Preprocessing takes linear time, and each query is constant, meaning that the program should terminate with plenty of time remaining.
Time complexity:
Comments