原题链接: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.youkuaiyun.com/doc_sgl/article/details/52734082的增强版,把矩阵的每一行看做一次求统计直方图的最大面积。所有行的最大面积就是整个矩阵的最大面积。
首先把2559这道题改改看一下:
#include <stdio.h>
#include <stack>
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<SNode> 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 <stdio.h>
#include <stack>
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;
}
这才AC。

本文介绍了一种求解给定二进制矩阵中最大的全是1的子矩阵的方法。通过将每行视为直方图来计算最大面积,最终找出整个矩阵的最大子矩阵。提供了两种实现方式,一种使用栈,另一种使用数组进行优化。
4698

被折叠的 条评论
为什么被折叠?



