Editorial for LCC '22 Contest 1 S5 - Candy Staircase
Submitting an official solution before solving the problem yourself is a bannable offence.
Subtask 1 [20%]
For this subtask, it sufficed to iterate through each valid element in the grid. The key was to find an efficient way to calculate the range maximum of any subarray of a particular row. This could be accomplished by using independent sparse tables, one for each row. Then, for each element, you simply calculated the size of the bottom row (), and iterated to the top row, reducing the width of your query by each time.
This subtask also rewarded intended solutions with a suboptimal rectangle query
Subtask 2 [80%]
The idea here was to consider the sparse table algorithm - a query of size could be easily calculated if you knew the answer to all of the queries of size . Hence, if we wished to find the answer for all triangles with rows, we could find the answer to all triangles with rows, which used triangles with rows, which in turn used triangles with row. If we had an odd number of rows, then we could use triangles with rows, roughly preserving the "halving" behavior. Notice that we actually only need to consider distinct dimensions, allowing for an solution.
Now the problem becomes how we can "combine" triangles. Consider this figure, which decomposes a triangle with 6 rows and into a rectangle and two triangles with rows:
Then, in this case, if we calculate all triangles of size , we can also efficiently calculate all triangles of size .
So, our query becomes much simpler - calculating the maximum of a "rectangle shape". We can use a max-queue to do this (a helpful link is here; alternatively, you can use two max-stacks, one for the "front" of the queue when pushing and one for the "back" when popping).
Using this data structure, for any rectangle of height and width , we can use the max-queue to calculate the maximum in all rectangles (run it on each row as if it were an array). Then, iterate vertically, taking maximum of all rectangles (notice that we already know the maximum of each "row" of the rectangle).