POJ-3494 Largest Submatrix of All 1’s(单调栈)

Largest Submatrix of All 1’s
http://poj.org/problem?id=3494
Time Limit: 5000MS   Memory Limit: 131072K
     
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 ≤ mn ≤ 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

第一眼看反应是DP,以前做过求最大的正方形的,立刻爽快的交了一发,WA,仔细一看,本题是求最大的矩形,然后就不知道DP怎么做了,但是有影响以前听过DP的解法

只好按照题解的单调栈做法写(解法太巧妙了)

对每一行进行类似HDU-1506(POJ-2599)的单调栈做法,小矩形的高度h[j]就是从该行开始往上的最大的连续1的个数,进行完最后一行后,即可求得最大的矩形


#include <cstdio>
#include <cstring>
#include <algorithm>

using namespace std;

int n,m,h[100005],top,ans;

struct Node {
    int h,sta;//sta表示高度h的起始下标
}s[100005];

int main() {
    int hh,t;
    while(scanf("%d%d",&n,&m)==2) {
        memset(h,0,sizeof(h));
        ans=0;
        for(int i=1;i<=n;++i) {
            for(int j=1;j<=m;++j) {
                scanf("%d",&hh);
                h[j]=hh==0?0:h[j]+1;
            }

            t=m;
            h[++t]=-1;//令最后一个元素的下一个高度为-1,避免循环完毕后还要弹出栈中所有元素
            s[0].h=-1;
            s[0].sta=top=0;
            for(int k=1;k<=t;++k) {
                if(h[k]>=s[top].h) {
                    s[++top].h=h[k];
                    s[top].sta=k;//其起始下标就是自己的下标
                }
                else {
                    while(h[k]<s[top].h) {
                        ans=max(ans,(k-s[top].sta)*s[top].h);
                        --top;//弹出栈顶元素
                    }
                    s[++top].h=h[k];//其起始下标是弹出的最后一个元素的起始下标
                }
            }
        }
        printf("%d\n",ans);
    }
    return 0;
}


你可能感兴趣的:(poj,单调栈)