POJ 3494 Largest Submatrix of All 1’s

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 <iostream>
#include <sstream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <iomanip>
#include <utility>
#include <string>
#include <cmath>
#include <vector>
#include <bitset>
#include <stack>
#include <queue>
#include <deque>
#include <map>
#include <set>

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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值