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。






發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章