Largest Submatrix of All 1’s--POJ3494

原题链接: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 ≤ mn ≤ 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 <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。






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值