largest Rectangle in a histogram
http://acm.hdu.edu.cn/showproblem.php?pid=1506
http://poj.org/problem?id=2559
Time limit:2000/1000 MS (java/others) Memory limit:65536/32768 K (java/others)
Problem Description A histogram is a polygon composed of a sequence of rectangles aligned at a common base line. The rectangles has equal widths but could 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 is used to represent discrete distributions, e.g., the frequencies of characters in texts. Note the order of the rectangles, i.e, their heights, is important. Calculate the area of the largest rectangle in a histogram that's aligned at the common base line, too. The 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. Assume that 1 <= n <= 100000. Then follow n integers h1, ..., HN, where 0 <= hi <= 1000000000. These numbers denote the heights of the rectangles in histogram 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 is 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
Previously seen DP solution, the principle of the interval is similar to the monotone stack, but it has to sweep 2 times
After understanding the problem of monotonic stack and its application, it is found that these problems have become very simple
#include <cstdio>
#include <algorithm>
using namespace std;
int n,w,h[100005],top;
Long long ans;
The struct Node {
int h,sta;//sta denotes the starting subscript of the height H
}s[100005];
int main () {while
(scanf ("%d", &n), n!=0) {for
(int i=1;i<=n;++i) {
scanf ("%d", h+i);
}
h[++n]=-1;//the next height of the last element is-1, to avoid the loop after the completion of all the elements of the stack
s[0].h=-1;
S[0].sta=top=0;
ans=0;
for (int i=1;i<=n;++i) {
if (h[i]>=s[top].h) {
s[++top].h=h[i];
s[top].sta=i;//its starting subscript is its subscript
}
else {while
(h[i]<s[top].h) {
Ans=max (ans,1ll* (I-s[top].sta ) *s[top].h);
--top;//popup stack top element
}
s[++top].h=h[i];//Its starting subscript is the start subscript of the last element that pops up
}
}
printf ("%i64d\n", ans);
}
return 0;
}