题目链接: Maximal submatrix
大致题意
给定一个 n × m n \times m n×m的矩阵, 求满足要求的最大面积子矩阵.
要求: 该子矩阵的每一列从上向下看不递减.
解题思路
➡️题目弱化版点这里⬅️
单调栈
如果你做过了题目的弱化版, 你会发现这个题实际上是一个二维版本.
我们需要对于每一行都求一次答案即可.
AC代码
#include <bits/stdc++.h>
#define rep(i, n) for (int i = 1; i <= (n); ++i)
using namespace std;
typedef long long ll;
const int N = 2E3 + 10;
int a[N][N], h[N][N], l[N], r[N];
int main()
{
int t; cin >> t;
while (t--) {
int n, m; scanf("%d %d", &n, &m);
rep(i, n) rep(j, m) scanf("%d", &a[i][j]);
rep(j, m) rep(i, n) {
if (a[i - 1][j] <= a[i][j]) h[i][j] = h[i - 1][j] + 1;
else h[i][j] = 1;
}
ll res = 0;
rep(i, n) {
const auto& qaq = h[i];
stack<int> st;
rep(j, m) {
while (!st.empty() and qaq[st.top()] >= qaq[j]) st.pop();
l[j] = st.empty() ? 1 : (st.top() + 1);
st.push(j);
}
st = stack<int>();
for (int j = m; j >= 1; --j) {
while (!st.empty() and qaq[st.top()] >= qaq[j]) st.pop();
r[j] = st.empty() ? m : (st.top() - 1);
st.push(j);
}
rep(j, m) res = max(res, 1ll * (r[j] - l[j] + 1) * qaq[j]);
}
printf("%lld\n", res);
}
return 0;
}