Explanation
Let be the maximum number of continuous free cells on line starting from to the right. This can be precomputed. Similarly to Maximum Building I, we can also apply monotonic stacks to find
- , the last line above with cell such that
- , the last line under with cell such that
We can efficiently update the answer matrix with prefix sums and difference arrays. Having , and precomputed, we know the upper bound and the lower bound of the rectangle of width , i.e. how much it can expand above and below line maintaining width .
We'll do difference arrays on each column independently. Accordingly, the updates of the answer matrix look like this:
- increment by
- decrement by
- decrement by
- increment by
Finally, we add to i.e. a submatrix of size contains a submatrix of size .
Implementation
Time Complexity:
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!