Largest Rectangle in a Histogram-POJ2559

原題鏈接http://poj.org/problem?id=2559

Description

A histogram is a polygon composed of a sequence of rectangles aligned at a common base line. The rectangles have equal widths but may have different heights. For example, the figure on the left shows the histogram that consists of rectangles with the heights 2, 1, 4, 5, 1, 3, 3, measured in units where 1 is the width of the rectangles: 

Usually, histograms are used to represent discrete distributions, e.g., the frequencies of characters in texts. Note that the order of the rectangles, i.e., their heights, is important. Calculate the area of the largest rectangle in a histogram that is aligned at the common base line, too. The figure on the right shows the largest aligned rectangle for the depicted histogram.

Input

The input contains several test cases. Each test case describes a histogram and starts with an integer n, denoting the number of rectangles it is composed of. You may assume that 1<=n<=100000. Then follow n integers h1,...,hn, where 0<=hi<=1000000000. These numbers denote the heights of the rectangles of the histogram in left-to-right order. The width of each rectangle is 1. A zero follows the input for the last test case.

Output

For each test case output on a single line the area of the largest rectangle in the specified histogram. Remember that this rectangle must be aligned at the common base line.

Sample Input

7 2 1 4 5 1 3 3
4 1000 1000 1000 1000
0

Sample Output

8
4000


tips:

單調棧

思路:

index 0 1 2 3 4 5 6 7 8
height 0 2 1 4 5 1 3 3 0
棧內容(上面棧底) (0,0) (0,0)
(2,1)
(0,0)
(1,1)
(0,0)
(1,1)
(4,3)
(0,0)
(1,1)
(4,3)
(5,4)
(0,0)
(1,1)
(1,3)
(0,0)
(1,1)
(1,3)
(3,6)
(0,0)
(1,1)
(1,3)
(3,6)
(3,7)
 


代碼:

#include <stdio.h>
#include <stack>
using namespace std;

struct SNode{
	long long height;
	int startIdx;
	SNode(long long h, int idx):height(h), startIdx(idx){}
};

long long heightArr[100000];

long long getMaxArea(int num){
	long long maxArea = 0;
	stack<SNode> stk;
	stk.push(SNode(0, 0));

	for(int i = 0; i <= num; i++){
		long long curh = 0;
		if(i < num){
			curh = heightArr[i];
		}
		int curStartIdx = i + 1;
		while(curh < stk.top().height){
			SNode t = stk.top();
			curStartIdx = t.startIdx;
			long long curArea = t.height * (i + 1 - t.startIdx);
			if(curArea > maxArea) maxArea = curArea;
			stk.pop();
		}
		stk.push(SNode(curh, curStartIdx));
	}
	return maxArea;
}

int main(){
	int num;
	while(scanf("%d", &num) != EOF && num){
		for(int i=0; i< num; i++){
			scanf("%lld", heightArr + i);
		}
		printf("%lld\n", getMaxArea(num));
	}
	return 0;
}














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