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 ≤ 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
最大全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+5; inline int read(){ char c=getchar();int x=0,f=1; while(c<‘0‘||c>‘9‘){if(c==‘-‘)f=-1;c=getchar();} while(c>=‘0‘&&c<=‘9‘){x=x*10+c-‘0‘;c=getchar();} return x; } int n,m,tot[N],a,ans=0; struct data{ int h,l,pos; }st[N]; int top=0; int main(int argc, const char * argv[]) { while(scanf("%d%d",&n,&m)!=EOF){ ans=0; memset(tot,0,sizeof(tot)); for(int i=1;i<=n;i++){ top=0; for(int j=1;j<=m;j++){ a=read(); if(!a) tot[j]=-1; data t; t.h=++tot[j];t.l=1;t.pos=j; int right=0; 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 0; }
时间: 2024-10-10 02:38:06