HDU——T 1506 Largest Rectangle in a Histogram|| POJ——T 2559 Largest Rectangle in a Histogram

http://acm.hdu.edu.cn/showproblem.php?pid=1506  ||

http://poj.org/problem?id=2559

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 19316    Accepted Submission(s): 5829


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
 

 

Recommend
LL   |   We have carefully selected several similar problems for you:  1505 1069 1087 1058 1176 
 
计算出当前矩形可以向两侧延伸的最大长度,单调栈应用、、
 1 #include <algorithm>
 2 #include <cstdio>
 3 
 4 using namespace std;
 5 
 6 #define LL long long
 7 const int N(100000+15);
 8 LL n,top,ans;
 9 LL l[N],r[N],h[N];
10 
11 inline void read(LL &x)
12 {
13     x=0; LL ch=getchar();
14     for(;ch>'9'||ch<'0';) ch=getchar();
15     for(;ch>='0'&&ch<='9';ch=getchar()) x=ch-'0'+x*10;
16 }
17 
18 int main()
19 {
20     for(ans=-1;1;ans=-1)
21     {
22         read(n);if(!n) break;
23         for(int i=1;i<=n;i++)
24             read(h[i]),l[i]=r[i]=i;
25         for(int i=2;i<=n;i++)
26           for(;l[i]>1&&h[l[i]-1]>=h[i];)
27               l[i]=l[l[i]-1];
28         for(int i=n-1;i>=1;i--)
29           for(;r[i]<n&&h[r[i]+1]>=h[i];)
30               r[i]=r[r[i]+1];
31         for(int i=1;i<=n;i++)
32             ans=max(ans,(r[i]-l[i]+1)*h[i]);
33         printf("%lld\n",ans);
34     }
35     return 0;
36 }

 

posted @ 2017-08-18 20:10  Aptal丶  阅读(208)  评论(0编辑  收藏  举报