Largest Submatrix of All 1’s
Time Limit: 5000MS Memory Limit: 131072K
Total Submissions: 5903 Accepted: 2226
Case Time Limit: 2000MS
Description
Given a m-by-n (0,1)-matrix, of all its submatrices of all 1’s which is the largest? By largest we mean that the submatrix has the most elements.
Input
The input contains multiple test cases. Each test case begins with m and n (1 ≤ m, n ≤ 2000) on line. Then come the elements of a (0,1)-matrix in row-major order on m lines each with n numbers. The input ends once EOF is met.
Output
For each test case, output one line containing the number of elements of the largest submatrix of all 1’s. If the given matrix is of all 0’s, output 0.
Sample Input
2 2
0 0
0 0
4 4
0 0 0 0
0 1 1 0
0 1 1 0
0 0 0 0
Sample Output
0
4
Source
POJ Founder Monthly Contest – 2008.01.31, xfxyjwf
题意:
给一个m*n的01矩阵,找出其中最大的全1矩阵,输出其1的个数。
思路:
单调栈。同POJ2559,对每一行的每一个元素做预处理,将其转换成m个POJ2559问题,遍历所有行即可找出最大,时间复杂度约O(mn)。
#include<cstdio>
#include<cstring>
using namespace std;
const int maxn = 2000;
struct Node {
int height;
int index;
}st[maxn + 5];
int top;
int buf[maxn + 5];
int m, n, ans;
int main() {
int value, tmp;
while (scanf("%d%d", &m, &n) != EOF) {
memset(buf, 0, sizeof(buf));
ans = 0;
for (int i = 1; i <= m; ++i) {
for (int j = 1; j <= n; ++j) {
scanf("%d", &value);
if (value == 0)
buf[j] = 0;
else
buf[j] += 1;
}
buf[n + 1] = -1; // 最后包含一个-1的项,用于弹出栈中所有元素
st[0].height = -1; // 起始项
st[0].index = 0;
top = 1;
for (int k = 1; k <= n + 1; ++k) {
// 进栈
if (buf[k] >= st[top - 1].height) {
st[top].height = buf[k];
st[top].index = k;
++top;
}
// 循环出栈,维护栈单调
else {
while (buf[k] < st[top - 1].height) {
tmp = st[top - 1].height * (k - st[top - 1].index);
if (ans < tmp)
ans = tmp;
--top;
}
st[top++].height = buf[k];
}
}
}
printf("%d\n", ans);
}
return 0;
}