hdu 1506 Largest Rectangle in a Histogram (DP)

Largest Rectangle in a Histogram

Time Limit: 2000/1000 MS (Java/Others)Memory Limit: 65536/32768 K (Java/Others)

Total Submission(s): 12947Accepted Submission(s): 3653

Problem 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 34 1000 1000 1000 10000

Sample Output

84000

题目链接:?pid=1506

题目大意:n块宽为1,长不等的矩形木板,如图拼凑在一起,求木板覆盖范围内最大矩形的面积。

解题思路:每块木板向左向右延伸,l[i],r[i]记录木板a[i]能延伸范围的左右边界,s=(r[i]-l[i]+1)*a[i],即为木板 a[i]延伸后覆盖的最大矩形面积。注意从前往后更新l[i],从后往前更新r[i],能有效提高效率。

代码如下:

#include <stdio.h>long long a[100004],l[100004],r[100004];//l[maxn],r[maxn]表示左右边界坐标int main(){int n,i,d;while(scanf("%d",&n)!=EOF&&n){long long s=0;a[0]=a[n+1]=-1;for(i=1;i<=n;i++){scanf("%I64d",&a[i]);l[i]=r[i]=i; //初始化左右边界的坐标}for(i=1;i<=n;i++){while(a[i]<=a[l[i]-1]) //如果还能延伸到边界左边的木板,呃更新边界值。如果后一块木板小于前一块l[i]=l[l[i]-1];//那后一块必能延伸到前一块木板的边界,有效地减少了循环次数}for(i=n;i>=1;i–){while(a[i]<=a[r[i]+1])r[i]=r[r[i]+1];}for(i=1;i<=n;i–){d=(r[i]-l[i])+1;if(d*a[i]>s)s=d*a[i];}printf("%I64d\n", s);}return 0;}

,“人无完人金无足赤”,只要是人就不会是完美的,

hdu 1506 Largest Rectangle in a Histogram (DP)

相关文章:

你感兴趣的文章:

标签云: