Editorial for DMOPC '17 Contest 3 P5 - Picnic Planning
Submitting an official solution before solving the problem yourself is a bannable offence.
Author:
Let denote the
square in the
row of the park.
Let be the sum of
for all rectangles where
is the bottom right corner of the rectangle. Let
be the sum of
for the same rectangles. Let
be the smallest number such that
is blocked or outside the grid. Let
be the largest number smaller than
such that
. To find this
for each
in amortized
, a stack may be used.
Consider a rectangle which has its bottom left corner before or at the column and bottom right corner at
. Then this is a unique rectangle with its bottom right corner at
with its right side stretched to the
column. The length of this rectangle remains unchanged but its width increases by a certain amount, specifically
. As such, the sum of
for rectangles with their bottom left corner before or at the
column is
and the sum of
is
.
Now consider the rectangles with their bottom left corner after the column and bottom right corner at
. Since
is the largest number smaller than
such that
, any rectangle with height from
to
and width from
to
can have their bottom right corner at
and still fit. In fact, these are all the rectangles with their bottom left corner after the
column and bottom right corner at
. The sum of
and
in this case can be computed in
if the sum of
for all
has been precomputed.
To compute the final values of and
, take the sum of the corresponding results found in each case. So using this
relation, all
and
values for a single row can be computed in
. All the
values can be computed in
.
To find the sums of all , perform this algorithm and then rotate the grid and repeat the algorithm. The final answer is the sum of all the
values.
Time Complexity:
Comments