Editorial for COCI '21 Contest 6 #2 Zemljište


Remember to use this editorial only when stuck, and not to copy-paste code from it. Please be respectful to the problem author and editorialist.
Submitting an official solution before solving the problem yourself is a bannable offence.

Without loss of generality, assume that a \le b.

Let's fix the first and last row of the plot of land to be chosen. Now the goal is to determine the best left and right end columns of the plot of land. Since the rows are already fixed, when choosing columns we'll take only the cells between the two end rows. Therefore, using prefix sums we can calculate for each column the sum of all cells in that column which are between the two rows. Then the problem becomes the following: given a sequence of numbers determine which interval has sum closest to the numbers a and b.

This problem can be solved using the two pointers method. We'll keep track of two pointers (indices in the array) l and r, which will point to the leftmost and rightmost end of the interval respectively. We'll move the r pointer to the right while the sum of the range is smaller than a, and for this sum, we'll check if it's optimal. Then we'll move the pointer l one position to the right and again update r until the sum passes a. Each pointer will be moved a total of \mathcal O(n) times so the total time complexity of the algorithm (together with fixing the rows) is \mathcal O(n^3).


Comments

There are no comments at the moment.