2017省选拔(二)poj3494 Largest Submatrix of All 1’s (单调栈+预处理)

直击链接:点击打开链接

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 mlines 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
题目大意:给出一个01矩阵,求出全是1的矩阵的面积。

题解:既然让求面积,无非就是长乘以宽嘛。那么目标就是去找长和宽就行了。先看看长吧。这里长就是1矩阵的高度,这个我可以预处理出来,就是对每一行的1的高度是上一行中的高度+1。当此位置是0的时候高度就是0喽。这样的话,比如位置(i,j),如果(i,j)的是1的话,他所求得高度是以该行为最低边向上的高度。然后我对每一行再求以(i,j)为矩阵的高的宽度。求宽度就用单调栈就可以了。

ps:如果是单调栈的初学者,建议先看一下这个题 http://blog.csdn.net/txgang/article/details/70049705

#include 
#include 
#include 
#include 
#include 
#include 
#include 

using namespace std;

int mp[2222][2222];
int dp[2222][2222];
int l[2222][2222],r[2222][2222];

int main()
{
    int n,m;
    while(~scanf("%d%d",&n,&m))
    {
        memset(dp,0,sizeof(dp));
        for(int i=1; i<=n; i++)
        {
            for(int j=1; j<=m; j++)
            {
                scanf("%d",&mp[i][j]);
                if(mp[i][j])
                {
                    dp[i][j]+=dp[i-1][j]+1;
                }
                else dp[i][j]=0;
            }
        }
        for(int i=1; i<=n; i++)
        {
            dp[i][0]=-1;
            dp[i][m+1]=-1;
        }
        int mx=0;
        stacks;
        while(!s.empty())s.pop();
        for(int i=1; i<=n; i++)
        {
            while(!s.empty())s.pop();
            s.push(0);
            for(int j=1; j<=m; j++)
            {
                int k;
                for(k=s.top(); dp[i][j]<=dp[i][k]; k=s.top())
                {
                    s.pop();
                }
                l[i][j]=k+1;
                s.push(j);
            }
            while(!s.empty())s.pop();
            s.push(m+1);
            for(int j=m; j>=1; j--)
            {
                int k;
                for(k=s.top(); dp[i][j]<=dp[i][k]; k=s.top())
                {
                    s.pop();
                }
                r[i][j]=k-1;
                s.push(j);
            }
            int sum=0;
            for(int j=1; j<=m; j++)
            {
                sum=dp[i][j]*(r[i][j]-l[i][j]+1);
                mx=max(mx,sum);
            }
        }
        printf("%d\n",mx);
    }
    return 0;
}


你可能感兴趣的:(#,ACM-数据结构,#,ACM-算法设计)