Largest Rectangle in a Histogram
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 7038 Accepted Submission(s): 1982
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
1/**//*用dp方法解决,首先是对于每个h[i],都有s[i]=h[i]*(r-j+1),r为从i右边第一个起,若好h[r]>=h[i],则r++;左边同理
2最后求出max(s[i])即可*/
3#include<cstdio>
4#include<iostream>
5using namespace std;
6#define INF 100010
7int l[INF],r[INF],n,i;
8int main()
9{
10 _int64 h[INF],s,max; // 结果可能超出int,h初始为__int64 或运算前强转化为__int64。运算过程中int会溢出
11 while(cin>>n&&n)
12 {
13 s=0;
14 for(i=1;i<=n;i++)
15 {
16 scanf("%I64d",&h[i]);
17 l[i]=r[i]=i;
18
19 }
20 h[0]=h[n+1]=-1;//题目中h[i]可能为0,初始化height数组为-1,防止死循环。
21 for(i=1;i<=n;i++)
22 {
23 while(h[l[i]-1]>=h[i])//左移
24 l[i]=l[l[i]-1];
25
26 }
27 for(i=n;i>=1;i--)
28 {
29 while(h[r[i]+1]>=h[i]) //右移
30
31 r[i]=r[r[i]+1];
32 }
33 max=0;
34 for(i=1;i<=n;i++)
35 {
36 s=h[i]*(r[i]-l[i]+1);
37 max=s>max? s:max;
38
39 }
40 printf("%I64d\n",max);
41
42 }
43 return 0;
44}PS:有无有更加快速的方法呢,时间上还是比较慢
posted on 2013-05-01 23:19
天YU地___PS,代码人生 阅读(184)
评论(0) 编辑 收藏 所属分类:
acm