POJ3494Largest Submatrix of All 1’s[单调栈]

Largest Submatrix of All 1’s
Time Limit: 5000MS   Memory Limit: 131072K
Total Submissions: 5883   Accepted: 2217
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

Source


最大全1子矩阵

对于每一行,维护一个全1高度(tot)递减栈就行了
注意0时tot[j]=-1,相当于一个高度为0的
最后依旧要弹出栈里的,如果没有上一行连sample都错
注意l已经包含了这个点,最后+n-st[top].pos不需要再+1
//
// main.cpp
// poj3494
//
// Created by Candy on 10/5/16.
// Copyright © 2016 Candy. All rights reserved.
// #include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
typedef long long ll;
const int N=2e3+;
inline int read(){
char c=getchar();int x=,f=;
while(c<''||c>''){if(c=='-')f=-;c=getchar();}
while(c>=''&&c<=''){x=x*+c-'';c=getchar();}
return x;
}
int n,m,tot[N],a,ans=;
struct data{
int h,l,pos;
}st[N];
int top=;
int main(int argc, const char * argv[]) {
while(scanf("%d%d",&n,&m)!=EOF){
ans=;
memset(tot,,sizeof(tot));
for(int i=;i<=n;i++){
top=;
for(int j=;j<=m;j++){
a=read();
if(!a) tot[j]=-;
data t;
t.h=++tot[j];t.l=;t.pos=j;
int right=;
while(top&&st[top].h>=t.h){
ans=max(ans,(st[top].l+right)*st[top].h);
//printf("%d %d %d %d %d %d\n",i,j,ans,st[top].l,right,st[top].h);
right+=st[top].l; t.l+=st[top].l;
top--;
}
st[++top]=t;//printf("top %d\n",top);
}//printf("toptop %d\n",top);
while(top){
ans=max(ans,st[top].h*(st[top].l +n-st[top].pos));
//printf("p %d %d %d %d\n",st[top].h,st[top].pos,st[top].l,ans);
top--;
}
}
printf("%d\n",ans);
} return ;
}
 
上一篇:例题6-3 Matrix Chain Multiplication ,Uva 442


下一篇:UVA——442 Matrix Chain Multiplication