题目:http://acm.hdu.edu.cn/showproblem.php?pid=1506
Largest Rectangle in a Histogram
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 14321 Accepted Submission(s): 4110
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
Source
University of Ulm Local Contest 2003
分析:dp思想,保留相关值,在后期计算时直接应用,避免大量的重复计算。具体见下:
/*
要求出相邻的同水平高度小矩形组成的最大面积,对于每一个单位柱状矩形,
需要求出不它比它低的最左边的柱形下标q1,还需要求出不比他低的最右边的柱形下标q2,
那么相应的矩形的面积就是(q2-q1+1)*h[i]. 所以找出每个单位矩形的左右q1,q2下标就能
解决问题。单纯的暴力肯定是超时的,设q1,q2相应的数组是l[],r[],利用本身的性质,
有这样的迭代关系可以更快的寻找q1,q2:if(h[q1]>=h[i]) q1=l[q1];
*/
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
typedef long long LL;
const int maxn=1e5+10;
LL h[maxn],area[maxn],l[maxn],r[maxn];
int main()
{
//freopen("cin.txt","r",stdin);
LL n,i,q1,q2;
while(cin>>n&&n){
for(i=1;i<=n;i++) scanf("%lld",&h[i]);
l[1]=1;
r[n]=n;
for(i=2;i<=n;i++){
q1=i;
while(q1>1&&h[q1-1]>=h[i]){ //hi有可能等于0所以一定要q1>1
q1=l[q1-1];
}
l[i]=q1;
}
for(i=n-1;i>=1;i--){
q2=i;
while(q2<n&&h[q2+1]>=h[i]){ //hi有可能等于0所以一定要q2<n
q2=r[q2+1];
}
r[i]=q2;
}
LL ans=0;
for(i=1;i<=n;i++){
area[i]=(r[i]-l[i]+1)*h[i];
ans=max(ans,area[i]);
}
printf("%lld\n",ans);
}
return 0;
}