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
題意:
給一個(gè)m*n的01矩陣,找出其中最大的全1矩陣,輸出其1的個(gè)數(shù)。
思路:
單調(diào)棧。同POJ2559,對(duì)每一行的每一個(gè)元素做預(yù)處理,將其轉(zhuǎn)換成m個(gè)POJ2559問(wèn)題,遍歷所有行即可找出最大,時(shí)間復(fù)雜度約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; // 最后包含一個(gè)-1的項(xiàng),用于彈出棧中所有元素
st[0].height = -1; // 起始項(xiàng)
st[0].index = 0;
top = 1;
for (int k = 1; k <= n + 1; ++k) {
// 進(jìn)棧
if (buf[k] >= st[top - 1].height) {
st[top].height = buf[k];
st[top].index = k;
++top;
}
// 循環(huán)出棧,維護(hù)棧單調(diào)
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;
}