Table of Contents

ExplanationImplementation

Explanation

Let ri,jr_{i,j} be the maximum number of continuous free cells on line ii starting from (i,j)(i, j) to the right. This can be precomputed. Similarly to Maximum Building I, we can also apply monotonic stacks to find

  1. ui,ju_{i, j}, the last line above ii with cell (x,j)(x, j) such that rx,j>ri,jr_{x, j} > r_{i, j}
  2. di,jd_{i, j}, the last line under ii with cell (y,j)(y, j) such that ry,jri,jr_{y, j} \ge r_{i, j}

We can efficiently update the answer matrix with prefix sums and difference arrays. Having ri,jr_{i,j}, ui,ju_{i,j} and di,jd_{i,j} precomputed, we know the upper bound and the lower bound of the rectangle of width ri,jr_{i,j}, i.e. how much it can expand above and below line ii maintaining width ri,jr_{i, j}.

We'll do difference arrays on each column independently. Accordingly, the updates of the answer matrix look like this:

  • increment ans[1][ri,j]\texttt{ans}[1][r_{i,j}] by 11
  • decrement ans[iui,j+2][ri,j]\texttt{ans}[i - u_{i, j} + 2][r_{i,j}] by 11
  • decrement ans[di,ji+2][ri,j]\texttt{ans}[d_{i,j} - i + 2][r_{i, j}] by 11
  • increment ans[di,jui,j+3][ri,j]\texttt{ans}[d_{i,j} - u_{i,j} + 3][r_{i,j}] by 11

Finally, we add ans[i][j]ans[i][j] to ans[i][j1]ans[i][j-1] i.e. a submatrix of size i×ji \times j contains a submatrix of size i×(j1)i \times (j-1).

Implementation

Time Complexity: O(NM)\mathcal{O}(N \cdot M)

C++

#include <iostream>
#include <stack>
#include <vector>
using namespace std;
int main() {
int n, m;
cin >> n >> m;
vector<vector<int>> r(n + 2, vector<int>(m + 2));

Python

n, m = map(int, input().split())
r = [[0] * (m + 2) for _ in range(n + 2)]
u = [[0] * (m + 1) for _ in range(n + 1)]
d = [[0] * (m + 1) for _ in range(n + 1)]
ans = [[0] * (m + 3) for _ in range(n + 3)]
mat = [[""] * (m + 1) for _ in range(n + 1)]
for i in range(1, n + 1):
row = input().strip()

Join the USACO Forum!

Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!