原题链接:http://poj.org/problem?id=3494
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
思路:
这道题是http://blog.csdn.net/doc_sgl/article/details/52734082的增强版,把矩阵的每一行看做一次求统计直方图的最大面积。所有行的最大面积就是整个矩阵的最大面积。
首先把2559这道题改改看一下:
#include
#include
using namespace std;
struct SNode{
int h;
int si;
SNode(){}
SNode(int _h, int _si):h(_h),si(_si){}
};
int m, n;
int h[2001];
int main(){
int maxarea = 0;
while(scanf("%d%d", &m, &n) != EOF){
maxarea = 0;
memset(h, 0, (n+1) * sizeof(h[0]));
for(int i = 0; i < m; i++){
stack stk;
stk.push(SNode(0,0));
int j = 0, x = 0;
for(; j < n; j++){
scanf("%d", &x);
if(x == 1) h[j]++;
else h[j]=0;
int start_idx = j+1;
while(h[j] < stk.top().h){
SNode t = stk.top();
start_idx = t.si;
int area = t.h * (j + 1 - t.si);
maxarea = max(maxarea, area);
stk.pop();
}
stk.push(SNode(h[j], start_idx));
}
while(!stk.empty()){
maxarea = max(maxarea, stk.top().h * (j + 1 - stk.top().si));
stk.pop();
}
}
printf("%d\n", maxarea);
}//while
return 0;
}
#include
#include
using namespace std;
struct SNode{
int h;
int si;
SNode(){}
SNode(int _h, int _si):h(_h),si(_si){}
};
int m, n;
int h[2001];
SNode st[2001];
int main(){
int maxarea = 0;
while(scanf("%d%d", &m, &n) != EOF){
maxarea = 0;
memset(h, 0, (n+1) * sizeof(h[0]));
for(int i = 0; i < m; i++){
int top=0;
st[top++]=SNode(0,0);
int j = 0, x = 0;
for(; j < n; j++){
scanf("%d", &x);
if(x == 1) h[j]++;
else h[j]=0;
int start_idx = j+1;
while(h[j] < st[top-1].h){
SNode t = st[top-1];
start_idx = t.si;
int area = t.h * (j + 1 - t.si);
maxarea = max(maxarea, area);
top--;
}
st[top++]=SNode(h[j], start_idx);
}
while(top){
maxarea = max(maxarea, st[top-1].h * (j + 1 - st[top-1].si));
top--;
}
}
printf("%d\n", maxarea);
}//while
return 0;
}