# Maximal submatrix（直方图最大矩阵）

2021/7/21 19:48:27 浏览：

# Maximal submatrix

#include <bits/stdc++.h>

using namespace std;

int n, m, Max;
int a[2003][2003];
int h[2003][2003];
int l[2003], r[2003];
stack<int> s;

int main() {
#ifndef ONLINE_JUDGE
freopen("in.txt", "r", stdin);
freopen("out.txt", "w", stdout);
#endif
int T;
scanf("%d", &T);
while(T--) {
Max = 0;
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= m; ++j) {
scanf("%d", &a[i][j]);
}
}
for (int j = 1; j <= m; ++j) h[1][j] = 1;
for (int i = 2; i <= n; ++i) {
for (int j = 1; j <= m; ++j) {
h[i][j] = a[i][j] >= a[i - 1][j] ? h[i - 1][j] + 1 : 1;
}
}
for (int i = 1; i <= n; ++i) {
while(!s.empty()) s.pop();
for (int j = 1; j <= m; ++j) {
while(!s.empty() && h[i][j] <= h[i][s.top()]) s.pop();
if (s.empty()) l[j] = 1;
else l[j] = s.top() + 1;
s.push(j);
}
while(!s.empty()) s.pop();
for (int j = m; j >= 1; --j) {
while(!s.empty() && h[i][j] <= h[i][s.top()]) s.pop();
if (s.empty()) r[j] = m;
else r[j] = s.top() - 1;
s.push(j);
Max = max(Max, h[i][j] * (r[j] - l[j] + 1));
}
}
printf("%d\n", Max);
}
}