原題鏈接http://poj.org/problem?id=2559
Description
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
Output
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;
}