Title Link:HDU-1506
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 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.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.Test Instructions Description: A rectangle with a width of 1 and a height greater than or equal to 0 is given to find the largest rectangular area. algorithm Analysis: see the range of N, it is determined not to n*n, think about, for a rectangle I, find the leftmost and most right continuous higher than its position, for the rectangle i+1, if the i+1 height than I small, then the left side of the i+1 to find a continuous higher than it is the leftmost position, There is no need to compare i+1 and I, i+1 and i-1 again 、、、 because some of the previous parts have been compared by I, so we just need to compare the last record to the left.
1#include <iostream>2#include <cstdio>3#include <cstring>4#include <cstdlib>5#include <cmath>6#include <algorithm>7 #defineINF 0x7fffffff8 using namespacestd;9typedefLong LongLL;Ten Const intmaxn=100000+Ten; One A intN; - intL[MAXN],R[MAXN],AN[MAXN]; - the intMain () - { - while(SCANF ("%d", &n)!=eof &&N) - { + for(intI=1; i<=n; i++) {scanf ("%d", &an[i]); l[i]=r[i]=i;} -an[0]=an[n+1]=-1; +l[0]=l[n+1]=r[0]=r[n+1]=0; A for(intI=1; i<=n; i++.) at { - while(an[l[i]-1]>=An[i]) -l[i]=l[l[i]-1 ]; - } - for(intI=n; i>=1; i--) - { in while(an[r[i]+1]>=An[i]) -r[i]=r[r[i]+1 ]; to } +LL ans=0; - for(intI=1; i<=n; i++.) the { *ll Area= (LL) (r[i]-l[i]+1)*(LL) an[i]; $ if(Area>ans) ans=Area ;Panax Notoginseng } -printf"%i64d\n", ans); the } + return 0; A}
HDU 1506 largest Rectangle in a histogram construction