【单调栈】POJ_3494_Largest Submatrix of All 1’s

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 首先我们来看看MVC架构的示意图: 和访问者交互的是控制层(Controller层),控制器(controller...
    司马东阳阅读 354评论 0 0
  • 你觉得这个世界上最难追上的人是谁? 初中的时候,我觉得,世界上最难追上的人是刘翔博尔特,高中时身边的小伙伴们开始情...
    晏耀飞阅读 381评论 0 3
  • 本周某日上午某人因某稿被某领导大骂一番,当着某某某同事的面儿,还是,当然,以上是客观情况,主观上某人着实能为自己辩...
    竞走的蜗牛阅读 362评论 0 2
  • 此刻只能用一个猫头来形容心情
    成金阅读 215评论 0 2
  • 高楼大厦排排座, 四处无风夜难眠; 风扇一晚不停息, 大汗如雨泪涟涟。 注1:长沙不愧有火炉之称,连续高温,又高楼...
    亮靓_27d5阅读 1,153评论 32 48