Problem:
Largest Rectangle

Given a matrix (H × W) which contains only 1 and 0, find the area of the largest rectangle which only contains 0s.

Input

H W
c1,1 c1,2 ... c1,W
c2,1 c2,2 ... c2,W
:
cH,1 cH,2 ... cH,W

In the first line, two integers H and W separated by a space character are given. In the following H lines, ci,j, elements of the H × W matrix, are given.

Output

Print the area (the number of 0s) of the largest rectangle.

Constraints

1 ≤ H, W ≤ 1,400

Sample Input

4 5
0 0 1 0 0
1 0 0 0 0
0 0 0 1 0
0 0 0 1 0

Sample Output

6

Solution in C++ (judge verdict: Accepted)

#include <iostream>
#include <cstring>
#include <cstdlib>
#include <sstream>
#include <stack>
#include <queue>
#include <list>
#include <stdio.h>
#include <algorithm>
#define MAX 1400
#define INF 100000000
using namespace std;
typedef long long ll;
int g[MAX+1][MAX+1],dp[MAX+1][MAX+1],maxsize;
struct rectangle {
	int height;
	int pos;
};
void init(int w,int h)
{
	for(int i=0;i<h;i++)
	{
		for(int j=0;j<w;j++)
		{
			if(g[i][j]) dp[i][j]=0;
			else{
				dp[i][j]=(i>0)?dp[i-1][j]+1:1;
			}
		}
		dp[i][w]=0;//为了使得算法最终停止 
	}
}
void getBiggest(int w,int h)
{
	int mid;
	stack<rectangle> s;
	for(int i=0;i<h;i++)//每一行都计算一次； 
	{
		while(!s.empty()) s.pop();
		struct rectangle rects;
		for(int j=0;j<=w;j++)
		{
			rects.pos=j;rects.height=dp[i][j];
			if(s.empty()){
				s.push(rects);
			}else{
				if(s.top().height<rects.height){
					s.push(rects);
				}else if(s.top().height>rects.height){
					while(!s.empty()&&s.top().height>=rects.height){
						struct rectangle tmp;
						tmp=s.top();s.pop();
						mid=tmp.height*(j-tmp.pos);
						maxsize=max(maxsize,mid);//更新最大值 
						rects.pos=tmp.pos;//更新rect最左边坐标的位置以便入栈 
					}
					s.push(rects);
				}
				//else continue;
			}
			
		}
		
	}
}
int main()
{	
	int h,w;
	cin>>h>>w;
	for(int i=0;i<h;i++)
	{
		for(int j=0;j<w;j++)
		{
			scanf("%d",&g[i][j]);
		}
	} 
	init(w,h);
	getBiggest(w,h);
	cout<<maxsize<<endl;
}