2107:largest Rectangle in a histogram time limit:1 Sec Memory limit:64 MB
submit:777 solved:220
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.
InputThe input contains several test cases. Each test case describes a histogram and starts with an integer
n, denoting the number of rectangles it is compos Ed 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.
OutputThe For all test case is 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 34 1000 1000 1000 10000
Sample Output
84000
HINT
Huge input, scanf is recommended.
1#include <stdio.h>2 #defineMax_n 1000003 4 intN;5 intH[max_n];6 intL[max_n], r[max_n];7 intStack[max_n];8 9 Long LongMaxLong LongALong Longb)Ten { One return(A > B)?a:b; A } - - voidSolve () the { - //Calculate L - Long LongAns =0; - intt =0; + inti; - for(i =0; I < n; ++i) + { A while(T >0&& h[stack[t-1]] >=H[i]) att--; -L[i] = (T = =0) ?0: (stack[t-1] +1); -stack[t++] =i; - } - - //Calculate R int =0; - for(i = n-1; I >=0; --i) to { + while(T >0&& h[stack[t-1]] >=H[i]) -t--; theR[i] = (T = =0) ? n:stack[t-1]; *stack[t++] =i; $ }Panax Notoginseng - for(i =0; I < n; ++i) the { +Ans=max (ans, (Long Long) h[i]* (r[i]-l[i])); A } theprintf"%lld\n", ans); + } - $ intMainvoid){ $ //freopen ("A.txt", "R", stdin); - inti; - while(SCANF ("%d", &n)! = EOF && N! =0) the { - for(i =0; I < n; ++i)Wuyiscanf"%d", &h[i]); the solve (); - } Wu - return 0; About}
View Code
Largest Rectangle in a histogram