hdu 1506 Largest Rectangle in a Histogram
Largest Rectangle in a Histogram
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 8484 Accepted Submission(s): 2366
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 3
4 1000 1000 1000 1000
0
Sample Output
8
4000
Source
University of Ulm Local Contest 2003
Recommend
LL
//62MS 2572K 873 B C++ //矩形问题的dp,读完别人的结题报告后自己也写一下 /* * 首先我们是很难想到状态转移方程的,因此便换一个角度思考。 *在一个点上的最大的矩形面积就是等于(最大宽度*改点的高 ), *由于每点的高我们都知道,因此我们的目的就是求最大宽,一开始 *的想法是直接暴力,明显会超时,因此我们便换成一种类似递归求解 *的方法(当然不是我想出来的- -),先创建两个数组l[]、r[],作用: *l[]: 记录该点往左不符合条件的数量; *r[]:记录该点往右符合条件的数量+i;(目的在于得出宽和便于状态转移) * 因为求l[]和求r[]原理一样,我就只分析求l[]的~ *l[1]=1说明没有符合条件的点,循环从i=2开始,如果符没越界和高度比 *比较高,就状态跳转,转移到上一个符合条件的点上 *不懂就自己模拟几次,时间复杂度从暴力的O(n^2)变成了O(n*lgn) */ #include<stdio.h> #define N 100005 __int64 a[N]; __int64 l[N]; //记录该点往左不符合条件的数量 __int64 r[N]; //记录该点往右符合条件的数量+i int main(void) { int n; while(scanf("%d",&n),n) { for(int i=1;i<=n;i++) scanf("%I64d",&a[i]); int t; l[1]=1; r[n]=n; for(int i=2;i<=n;i++){ t=i; while(t>1 && a[i]<=a[t-1]) t=l[t-1]; l[i]=t; //printf("%d\n",l[i]); } for(int i=n-1;i>0;i--){ t=i; while(t<n && a[i]<=a[t+1]) t=r[t+1]; r[i]=t; //printf("%d\n",r[i]); } __int64 max=0; for(int i=1;i<=n;i++){ if(max<a[i]*(r[i]-l[i]+1)) max=a[i]*(r[i]-l[i]+1); } printf("%I64d\n",max); } return 0; }