Editorial for COCI '12 Contest 4 #6 Akvarij
Submitting an official solution before solving the problem yourself is a bannable offence.
The area below the aquarium bottom consists of trapezoids. We will find a way to calculate the area of one trapezoid and then improve it using data structures for faster work with all of them. For the sake of simplicity, we calculate the area of the unflooded part below the water level .
There are three cases for a trapezoid:
- Water area is above the entire trapezoid.
- Water area is below both upper vertices of the trapezoid.
- Water area is between the upper vertices of the trapezoid.
In the first case, the area is equal to the area of the entire trapezoid.
In the second case, the area is equal to the water height .
In the third case, we calculate the area in the form (determining polynomial coefficients is left as an exercise to the reader).
In case there are more trapezoids, for a height we can divide them into groups 1, 2, 3 above. From the first group we need the sum of all areas, from the second we need the number of trapezoids (the total area in this group is equal to ), and from the third we need the sum of corresponding polynomial coefficients, from which we can get a formula for the area of the group.
The problem is calculating the sum fast enough for each group. If for a given we present each trapezoid as a point , groups become rectangles as shown below:
Queries on such 2D intervals can be done using a 2D Fenwick tree. In each element of the structure, we store the sum of total areas, number of trapezoids and three sums of coefficients (, and ). This structure is simply maintained when we change the height, and the complexity of a query is . The total complexity of the algorithm is .
There are alternative solutions. Instead of maintaining the structure of trapezoids, we can maintain the array of solutions for each . For each height, we are interested in the same three cases as before. If we have a trapezoid (for the sake of simplicity assume ), it contributes to the interval with its total area, to the interval with its formula (see case 3), and to the interval with increasing the number of trapezoids by . The array of solutions can once again be achieved as a Fenwick tree or a tournament tree and the complexity of an operation is then , in total .
Comments