首页 > 代码库 > Largest Rectangle in a Histogram

Largest Rectangle in a Histogram

2107: Largest Rectangle in a Histogram

Time Limit: 1 Sec  Memory Limit: 64 MB
Submit: 777  Solved: 220

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

HINT

Huge input, scanf is recommended.

技术分享
 1 #include <stdio.h> 2 #define MAX_N 100000 3  4 int n; 5 int h[MAX_N]; 6 int L[MAX_N], R[MAX_N]; 7 int stack[MAX_N]; 8  9 long long max(long long a, long long b)10 {11     return (a > b) ? a : b;12 }13 14 void solve()15 {16     //计算L17     long long ans = 0;18     int t = 0;19     int i;20     for (i = 0; i < n; ++i)21     {22         while (t > 0 && h[stack[t-1]] >= h[i])23             t--;24         L[i] = (t == 0) ? 0 : (stack[t-1] + 1);25         stack[t++] = i;26     }27 28     //计算R29     t = 0;30     for (i = n - 1; i >= 0; --i)31     {32         while (t > 0 && h[stack[t-1]] >= h[i])33             t--;34         R[i] = (t == 0) ? n : stack[t-1];35         stack[t++] = i;36     }37 38     for (i = 0; i < n; ++i)39     {40         ans=max ( ans, ( long long)h[i]*( R[i]- L[i]));41     }42     printf("%lld\n", ans);43 }44 45 int main(void){46    // freopen("a.txt","r",stdin);47     int i;48     while (scanf("%d", &n) != EOF && n != 0)49     {50         for (i = 0; i < n; ++i)51             scanf("%d", &h[i]);52         solve();53     }54 55     return 0;56 }
View Code

 

Largest Rectangle in a Histogram