Language: Default Largest Submatrix of All 1’s
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 |
题意:给出一个n*m的矩阵,这个矩阵的元素为0或1,要求找出一个子矩阵,满足:
1.都是由1组成
2.矩阵的面积最大
这道题,其实就是POJ2559的加强版
a[i][j]表示:第i行,以第j列为底的矩阵的最大高度。
之后,枚举每一列,相当于以每一列为底的条形图,求最大的矩形面积(就是POJ2559了)
注意:我这份代码交了3次,2次ac,1次tle,因为有些单样例tle了,下次再修改一下。
1 #include<cstdio> 2 #include<cstring> 3 #include<algorithm> 4 #include<stack> 5 using namespace std; 6 7 const int maxn=2005; 8 9 int a[maxn][maxn]; 10 int L[maxn]; 11 int R[maxn]; 12 struct Node 13 { 14 int num,h; 15 }node[maxn]; 16 17 int solve(int n,int cnt) 18 { 19 for(int i=1;i<=n;i++) 20 { 21 node[i].h=a[i][cnt]; 22 node[i].num=i; 23 } 24 node[0].num=0; 25 node[0].h=0; 26 n++; 27 node[n].num=n; 28 node[n].h=0; 29 stack<Node>s; 30 s.push(node[0]); 31 for(int i=1;i<=n;i++) 32 { 33 if(node[i].h>=s.top().h) 34 s.push(node[i]); 35 else 36 { 37 while(s.top().h>node[i].h) 38 { 39 Node tmp=s.top(); 40 s.pop(); 41 R[tmp.num]=i; 42 L[tmp.num]=s.top().num; 43 } 44 s.push(node[i]); 45 } 46 } 47 int ans=-1; 48 for(int i=1;i<n;i++) 49 { 50 ans=max(ans,node[i].h*(R[i]-L[i]-1)); 51 } 52 return ans; 53 } 54 55 int main() 56 { 57 int row,col; 58 while(~scanf("%d%d",&row,&col)) 59 { 60 for(int i=1;i<=row;i++) 61 { 62 a[i][0]=0; 63 for(int j=1;j<=col;j++) 64 { 65 scanf("%d",&a[i][j]); 66 if(a[i][j-1]&&a[i][j]) 67 { 68 a[i][j]+=a[i][j-1]; 69 } 70 } 71 } 72 int ans=-1; 73 for(int j=1;j<=col;j++) 74 { 75 ans=max(ans,solve(row,j)); 76 } 77 printf("%d\n",ans); 78 79 } 80 return 0; 81 }
POJ 3494 Largest Submatrix of All 1's 栈的运用 好题