Editorial for COCI '13 Contest 1 #3 Ratar
Submitting an official solution before solving the problem yourself is a bannable offence.
The first step towards solving this problem is finding a way to quickly compute the total income of a rectangular field. We will first describe a good solution to that subproblem.
It is possible to precompute in advance an
This precomputation is useful since we can then determine the total income of any rectangle in time
A simple way of finding all valid rectangle pairs is trying out all possible quadruples of points as opposite corners of the two rectangles and checking whether they have the same sum using the formula above. This solution has a complexity of
The solution above can be easily optimized by iterating over triples instead of quadruples, immediately fixing the common vertex of the two rectangles. This reduces the complexity to
For the final optimization, we can exploit the fact that individual unit square incomes are restricted to the interval between
We will demonstrate the idea in the case of rectangles sharing the upper left and lower right corners, as in the picture. We first iterate over all possible common rectangle vertices. Then, for a fixed common vertex, we iterate over all possible upper left corners of rectangle 1 and use the array to track the number of rectangles 1 for each possible sum. After that, we iterate over all possible lower right corners of rectangle 2 and, for each rectangle 2 with a sum
The complexity of the algorithm described above is
Comments