您的位置:首页 > 其它

POJ 3494 Largest Submatrix of All 1's 栈的运用 好题

2015-05-30 10:55 381 查看
Language:
Default

Largest Submatrix of All 1’s

Time Limit: 5000MSMemory Limit: 131072K
Total Submissions: 5185Accepted: 1950
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
题意:给出一个n*m的矩阵,这个矩阵的元素为0或1,要求找出一个子矩阵,满足:

1.都是由1组成

2.矩阵的面积最大

这道题,其实就是POJ2559的加强版

a[i][j]表示:第i行,以第j列为底的矩阵的最大高度。

之后,枚举每一列,相当于以每一列为底的条形图,求最大的矩形面积(就是POJ2559了)

注意:我这份代码交了3次,2次ac,1次tle,因为有些单样例tle了,下次再修改一下。

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<stack>
using namespace std;

const int maxn=2005;

int a[maxn][maxn];
int L[maxn];
int R[maxn];
struct Node
{
int num,h;
}node[maxn];

int solve(int n,int cnt)
{
for(int i=1;i<=n;i++)
{
node[i].h=a[i][cnt];
node[i].num=i;
}
node[0].num=0;
node[0].h=0;
n++;
node
.num=n;
node
.h=0;
stack<Node>s;
s.push(node[0]);
for(int i=1;i<=n;i++)
{
if(node[i].h>=s.top().h)
s.push(node[i]);
else
{
while(s.top().h>node[i].h)
{
Node tmp=s.top();
s.pop();
R[tmp.num]=i;
L[tmp.num]=s.top().num;
}
s.push(node[i]);
}
}
int ans=-1;
for(int i=1;i<n;i++)
{
ans=max(ans,node[i].h*(R[i]-L[i]-1));
}
return ans;
}

int main()
{
int row,col;
while(~scanf("%d%d",&row,&col))
{
for(int i=1;i<=row;i++)
{
a[i][0]=0;
for(int j=1;j<=col;j++)
{
scanf("%d",&a[i][j]);
if(a[i][j-1]&&a[i][j])
{
a[i][j]+=a[i][j-1];
}
}
}
int ans=-1;
for(int j=1;j<=col;j++)
{
ans=max(ans,solve(row,j));
}
printf("%d\n",ans);

}
return 0;
}


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