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

题意:给了一个只有0和1组成的m*n的矩阵,求出由1组成的最大的矩阵中1的个数。

解题思路:这个题挺好的。用num数组记录下来每一列1的个数(相当于一个矩形的高h)只要是连续地就不停地加,不连续就重新赋值为0,然后在每一行中进行计算,每一行都维护一个单调递减的栈,每一行中栈的初始值为-1,num的最终值为-1.同时用sub数组记录下标(相当于矩形的边长)。当遇到比栈顶元素小的值的时候,就开始向前遍历计算矩形的面积(即1的个个数),每次记录下最大值即可

又卡cin了。

#include
#include
#include
using namespace std;
int main()
{
    int n,m;
    while(~scanf("%d%d",&m,&n))
    {
        int num[3000]= {0};
        int i,j,k;
        int ans=0;
        for(i=1; i<=m; i++)
        {
            for(j=1; j<=n; j++)
            {
                int x;
                scanf("%d",&x);
                if(x==1)
                    num[j]++;//如果上下连续就一直加
                else
                    num[j]=0;//不连续就重新赋值为0
            }
            stack<int>s;
            int t=n+1;
            num[t]=-1;   ///让num数组的最后面为-1,方便最后弹出栈中的元素
            s.push(-1);
            int sub[3000]= {0};
            for(k=1; k<=t; k++)
            {
                if(num[k]>=s.top())//如果比栈顶元素大就入栈
                {
                    s.push(num[k]);
                    sub[s.size()]=k;
                }
                else
                {
                    while(num[k]int area=(k-sub[s.size()])*s.top();//计算面积
                        if(area>ans)
                            ans=area;
                        s.pop();
                    }
                    s.push(num[k]);
                }
            }
        }
        cout<

你可能感兴趣的:(ACM)