您的位置:首页 > 其它

poj 3494 Largest Submatrix of All 1’s 单调栈/DP迭代法

2016-07-10 23:56 489 查看
题意:给出一个m*n的01矩阵,问在系数全为1的子矩阵中 系数和的最大值。

解法:DP中的迭代法,或者单调栈。

不论哪种方法核心都是对于每个高度为h的矩形,找到最左高度大于等于它的位置,和最右的位置。

#include<cstdio>
#include<string>
#include<cstring>
#include<iostream>
#include<cmath>
#include<algorithm>
#include<vector>
using namespace std;

#define all(x) (x).begin(), (x).end()
#define for0(a, n) for (int (a) = 0; (a) < (n); (a)++)
#define for1(a, n) for (int (a) = 1; (a) <= (n); (a)++)
typedef long long ll;
typedef pair<int, int> pii;
const int INF =0x3f3f3f3f;
const int maxn= 2000 ;

struct Node
{
int h;
int le;
};
int n,m,ans;
int h[maxn+10];

Node sta[maxn+10];
int main()
{
while(~scanf("%d%d",&m,&n))
{
int x,ans=0;
memset(h,0,(n+1)*sizeof h[0]);
for1(i,m)
{
int top=0;
for1(j,n)
{
scanf("%d",&x);
if(!x) h[j]=0;
else h[j]++;

if(top&&sta[top].h>h[j])
{
while(top&&sta[top].h>h[j])
{
ans=max(ans, sta[top].h*(j-sta[top].le) );
top--;
}
sta[++top].h=h[j];
}
else
{
sta[++top].h=h[j];
sta[top].le=j;
if(top>=2&&sta[top-1].h==sta[top].h ) sta[top].le=sta[top-1].le;
}
}
while(top)
{
ans=max(ans,sta[top].h*( n+1- sta[top].le) );
top--;
}
}
printf("%d\n",ans);

}

return 0;
}

/*
4 4
1 0 0 0
1 1 1 1
0 1 1 1
1 0 0 1

*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: