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
题目大意:
给定一个M x N的01矩阵, 找出最大的全1子矩阵。
解题思路:
数据量是2000, 如果枚举每一个位置能拓展的矩阵大小会超时, 所以我们需要逐行枚举, 用一个栈去维护一个递增的K x 1的矩阵, 当遇到一个下降的矩阵时就向前拓展看它最长能拓展的大小, 输出那个最大的答案即可(思路与POJ 2559相同)。
代码:
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
/*
*ios::sync_with_stdio(false);
*/
typedef long long ll;
typedef unsigned long long ull;
const int dir[5][2] = {0, 1, 0, -1, 1, 0, -1, 0, 0, 0};
const ll ll_inf = 0x7fffffff;
const int inf = 0x3f3f3f;
const int mod = 1000000;
const int Max = 2010;
int n, m;
int arr[Max][Max], h[Max];
int main() {
// initialization
while (~scanf("%d %d", &n, &m)) {
memset(h, 0 ,sizeof(h));
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= m; ++j) {
scanf("%d", &arr[i][j]);
}
}
int ans = 0, l, w;
for (int i = 1; i <= n; ++i) {
// i-th 1 numbers
for (int j = 1; j <= m; ++j) {
h[j] = (arr[i][j] == 0) ? 0 : h[j] + 1;
}
// prevent overfull
stack < int> S; S.push(0); h[++m] = 0;
for (int j = 1; j <= m; ++j) {
while (h[j] < h[S.top()]) {
l = h[S.top()]; S.pop();
w = j - S.top() - 1;
ans = max(ans, l * w);
}
S.push(j);
}
--m;
}
printf("%d\n", ans);
}
return 0;
}