Largest Submatrix of All 1’s

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
#include
#include
#include
//     1    ,               

//     ,              ,       

//       ,1.           ,           ,        ,    
//    ,      h[][]      ,    ,      map[][] 0,          
//        ,               ,           ,          ,
//         00   ,    ,               、

//           ,    ,      ,
//    ,        ,    ,       ,           ,          ,
//            ,          max(),
//      
using namespace std;
stack <int> stk;
const int Max=2000+10;
int mp[Max][Max];
int m,n;
int h[Max][Max];//        1   
int l[Max],r[Max];
int main()
{

   memset(mp,0,sizeof(mp));
   memset(h,0,sizeof(mp));
   while(~scanf("%d %d",&m,&n))
   {   int ans=0;
       for(int i=1;i<=m;i++)
        for(int j=1;j<=n;j++)
        {
           scanf("%d",&mp[i][j]);
           h[i][j]= mp[i][j]==0?0:h[i-1][j]+1;//            
        }
      for(int i=1;i<=m;i++)//      ,     
      {
          stack<int> stk1;//            ,          ,      ,       
                          //          ,     
          for(int j=1;j<=n;j++)
          {
              while(!stk1.empty()&&h[i][j]<=h[i][stk1.top()])
                stk1.pop();
              l[j]=stk1.empty()? 1: stk1.top()+1;
              stk1.push(j);
          }
          stack<int> stk2;
          for(int j=n;j>=1;j--)
          {
              while(!stk2.empty()&&h[i][j]<=h[i][stk2.top()])
                stk2.pop();
              r[j]=stk2.empty()?n:stk2.top()-1;
              stk2.push(j);
          }
          for(int j=1;j<=n;j++)
          {
              int s;
              s=h[i][j]*(r[j]-l[j]+1);
              ans=max(ans,s);
          }
      }
      printf("%d
"
,ans); } return 0; }

좋은 웹페이지 즐겨찾기