201312-3 最大的矩形

思路

每输入一个新的直方矩阵就做一次最大面积的判断,3个可能最大面积:

  • k-1块最大面积
  • k-1块最大面积情形合并第k块
  • 从第k块开始向前推导重新获得最大面积

实现

#include <iostream>

#define MAXN 0xfff

using namespace std; 

typedef struct _Max_Rectangle {
	int begin_rectangle;
	int end_rectangle;
	int height;
} max_rectangle_str;

int main () {
	int num;
	int cube_heights[MAXN] = {0};
	max_rectangle_str max = {0,0,0};
	
	cin >> num;

	int i;
	for (i = 0;i < num;++i) {
		cin >> cube_heights[i];
		
		if (max.height == 0) {
			max.height = cube_heights[i];
			max.begin_rectangle = i;
			max.end_rectangle = i;
		} else {
			if (max.end_rectangle == i - 1 
			&& cube_heights[i] >= max.height) {
				max.end_rectangle += 1;
			} 
			int cur_width = max.end_rectangle - max.begin_rectangle + 1;
			int cur_area = cur_width * max.height;
			
			int new_height = cube_heights[i], new_begin_index = i;
			int new_area = new_height;
			int cur_height = new_height; 
			int j;
			for (j = i - 1;j >= 0;--j) {
				if (cur_height > cube_heights[j]) {  
					cur_height = cube_heights[j];
				} 
				int area_temp = cur_height * (i - j + 1);
				if (area_temp > new_area) {
					new_height = cur_height;
					new_begin_index = j;
					new_area = area_temp;
				}
			}
			if (new_area > cur_area) {
				max.end_rectangle = i;
				max.begin_rectangle = new_begin_index;
				max.height = new_height;
			}
		} 
	}
	cout << (max.end_rectangle - max.begin_rectangle + 1) * max.height;
}
posted @ 2020-08-17 23:08  amonqsq  阅读(69)  评论(0编辑  收藏  举报