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  matrix 
, where 
 contains the sum of values in the rectangle with opposite corners in 
 and 
. For the purposes of this problem, it is sufficient to calculate the matrix values with 
 time complexity, iterating over the whole rectangle for each matrix cell. Of course, it is possible to carry out the computation in 
, which is left as an exercise for the reader.
This precomputation is useful since we can then determine the total income of any rectangle in time  instead of 
 using the inclusion-exclusion formula:
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  and yields 
 of points.
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  and yields 
 of points.
For the final optimization, we can exploit the fact that individual unit square incomes are restricted to the interval between  and 
, which means that the total income of any rectangle falls between 
 and 
. Since 
 is at most 
, we can use an array of size 
 to count the rectangles with each possible total income.
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 , look up the number of rectangles 1 with the same sum 
 and add that number to the solution. We repeat an equivalent procedure for rectangle pairs sharing the lower left and upper right corners.
The complexity of the algorithm described above is  and it is sufficient to score 
 of points.
Comments