UVa 10360 - Rat Attack

Summary
Baaaam! Another deadly gas bomb explodes in Manhattan’s underworld. Rats have taken over the sewerage and the city council is doing everything to get the rat population under control. As you know, Manhattan is organized in a regular fashion with streets and avenues arranged like a rectangular grid. Waste water drains run beneath the streets in the same arrangement and the rats have always set up their nests below street intersections. The only viable method to extinguish them is to use gas bombs like the one which has just exploded. However, gas bombs are not only dangerous for rats. The skyscrapers above the explosion point have to be evacuated in advance and so the point of rat attack must be chosen very carefully. The gas bombs used are built by a company called American Catastrophe Management (ACM) and they are sold under the heading of “smart rat gas”. They are smart because — when fired — the gas spreads in a rectangular fashion through the under street canals. The strength of a gas bomb is given by a number d which specifies the rectangular “radius” of the gas diffusion area. For example, Figure 2 shows what happens when a bomb with d = 1 explodes.

Explanation
The area of interest consists of a discrete grid of 1025 × 1025 fields. Rat exterminator scouts have given a detailed report on where rat populations of different sizes have built their nests. You are given a gas bomb with strength d and your task is to find an explosion location for this gas bomb which extinguishes the largest number of rats. The best position is determined by the following criteria: • The sum of all rat population sizes within the diffusion area of the gas bomb (given by d) is maximal. • If there is more than one of these best positions then the location with the “minimal” position will be chosen. Positions are ordered first by their x coordinate and second by their y coordinate. Formally, given a location (x1, y1) on the grid, a point (x2, y2) is within the diffusion area of a gas bomb with strength d if the following equation holds: max (abs(x2 - x1), abs (y2 - y1)) <= d

Implementations
Notes/Hints on actual implementation here.

Short Explanation: Imagine that you compress each dxd square into a single number and place it at the center. Construct a new MXN matrix with these numbers in O(M*N) time. Once the matrix is updated, the maximum number in the grid is the answer.

Input
1 1 2 4 4 10 6 6 20

Output
5 5 30