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
单调栈,先预处理每列前i行连续1的长度,然后枚举行,用单调栈求出以每一行为底,求出的最大的矩形面积,最后求个最大值
封装好的栈有点慢。。。
/*************************************************************************
> File Name: POJ3494.cpp
> Author: ALex
> Mail: zchao1995@gmail.com
> Created Time: 2015年05月07日 星期四 22时01分58秒
************************************************************************/
#include <functional>
#include <algorithm>
#include <iostream>
#include <fstream>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <queue>
#include <stack>
#include <map>
#include <bitset>
#include <set>
#include <vector>
using namespace std;
const double pi = acos(-1.0);
const int inf = 0x3f3f3f3f;
const double eps = 1e-15;
typedef long long LL;
typedef pair <int, int> PLL;
static const int N = 2010;
int mat[N][N];
int col[N][N];
int L[N], R[N];
PLL st[N];
int Top;
int main() {
int n, m;
while (~scanf("%d%d", &n, &m)) {
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= m; ++j) {
scanf("%d", &mat[i][j]);
}
}
for (int j = 1; j <= m; ++j) { //第j列
col[0][j] = 0;
for (int i = 1; i <= n; ++i) {
if (mat[i][j] == 0) {
col[i][j] = 0;
}
else {
col[i][j] = col[i - 1][j] + 1; //第j列前i行
}
}
}
int ans = 0;
for (int i = 1; i <= n; ++i) {
Top = 0;
for (int j = 1; j <= m; ++j) {
L[j] = R[j] = j;
}
for (int j = m; j >= 1; --j) {
if (!Top) {
st[++Top] = (make_pair(col[i][j], j));
}
else {
while (Top) {
PLL u = st[Top];
if (u.first <= col[i][j]) {
break;
}
--Top;
L[u.second] = j + 1;
}
st[++Top] = (make_pair(col[i][j], j));
}
}
while (Top) {
PLL u = st[Top];
--Top;
L[u.second] = 1;
}
for (int j = 1; j <= m; ++j) {
if (!Top) {
st[++Top] = (make_pair(col[i][j], j));
}
else {
while (Top) {
PLL u = st[Top];
if (u.first <= col[i][j]) {
break;
}
--Top;
R[u.second] = j - 1;
}
st[++Top] = (make_pair(col[i][j], j));
}
}
while (Top) {
PLL u = st[Top];
--Top;
R[u.second] = m;
}
for (int j = 1; j <= m; ++j) {
int l = L[j];
int r = R[j];
ans = max(ans, (r - l + 1) * col[i][j]);
}
}
printf("%d\n", ans);
}
return 0;
}

本文介绍了一种高效算法来解决寻找给定0-1矩阵中最大全1子矩阵的问题。通过预处理每列连续1的数量,并使用单调栈求解以每行为底的最大矩形面积,最终找到整个矩阵中的最大全1子矩阵。
379

被折叠的 条评论
为什么被折叠?



