#B4222. Cube Construction
Cube Construction
Cube Construction
Little X is playing with blocks. Each block is a $1\times1\times1$ cube. The ground is modeled as an $n\times m$ grid. In the cell on the $i$th row and $j$th column, there are $h_{i,j}$ blocks stacked neatly from bottom to top.
Little X wants to remove some blocks so that the remaining blocks form a perfect cube, i.e. a cuboid whose length, width, and height are all equal. In other words, after removal the blocks left on the ground must exactly fill an axis‐aligned cube of side length $L$ (with $L^3$ blocks) and no other blocks remain.
To do this, one must select a contiguous subgrid of size $L\times L$ (for some $L\ge1$) such that every cell in that subgrid has at least $L$ blocks (so that it is possible to leave exactly $L$ blocks in that cell by removing the excess). All blocks outside this subgrid must be removed as well. Let the total number of blocks initially be $T=\sum_{i,j}h_{i,j}$. Then by leaving exactly $L$ blocks in each cell of the chosen subgrid, the number of blocks remaining is $L^3$, and the number of blocks removed is minimized if $L^3$ is maximized among all possible choices.
Your task is to compute the minimum number of blocks that must be removed so that the remaining blocks form a cube. It is guaranteed that there is at least one cell with at least one block so that a cube of side length $L\ge1$ can always be formed.
Note: If you choose a subgrid of size $L\times L$, you can only keep $L$ blocks in each cell (removing extra blocks if present), and all blocks outside that subgrid are removed. Hence, the answer is
$T - L^3$,
where $L$ is the maximum integer (with $1\le L\le \min(n,m)$) for which there exists a contiguous $L\times L$ subgrid in which every cell has at least $L$ blocks.
inputFormat
The first line contains two integers $n$ and $m$ --- the number of rows and columns of the grid.
Each of the next $n$ lines contains $m$ integers, where the $j$th integer of the $i$th line is $h_{i,j}$, the number of blocks in that cell.
outputFormat
Output a single integer --- the minimum number of blocks that must be removed so that the remaining blocks form a perfect cube.
sample
3 3
4 4 4
4 4 4
4 4 4
9