Language:
Largest Rectangle in a Histogram
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 Hint
Huge input, scanf is recommended.
Source |
题意:给出n个矩形的高,问它们能组成的最大矩形的面积是多少。
思路:定义两个数组 l[i] 和 r[i] ,分别记录从 i 点能向左向右扩展的最大位置。若a[i]<=a[ l[i] - 1 ],则 l[i] = l[ l[i] - 1](如果i可以扩展到l[i]-1处,那么在计算i之前l[i]-1处的l[l[i]-1]已经计算出来了,就可以直接令l[i]=l[l[i]-1]了);同理,若 a[i]<=a[ r[i] - 1 ],则 r[i] = r[ r[i] - 1]。这样做充分利用了之前已经计算出来的数据。
代码:
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #include <cmath> #include <string> #include <map> #include <stack> #include <vector> #include <set> #include <queue> #define maxn 100010 #define FRE(i,a,b) for(i = a; i <= b; i++) #define FREE(i,a,b) for(i = a; i >= b; i--) #define FRL(i,a,b) for(i = a; i < b; i++) #define FRLL(i,a,b) for(i = a; i > b; i--) #define mem(t, v) memset ((t) , v, sizeof(t)) #define sf(n) scanf("%d", &n) #define sff(a,b) scanf("%d %d", &a, &b) #define sfff(a,b,c) scanf("%d %d %d", &a, &b, &c) #define pf printf #define DBG pf("Hi\n") typedef long long ll; using namespace std; ll n; ll l[maxn],r[maxn],a[maxn]; int main() { ll i; while (scanf("%lld",&n)) { if (n==0) break; mem(a,0); FRE(i,1,n) scanf("%lld",&a[i]); a[0]=-1; a[n+1]=-1; FRE(i,1,n) { l[i]=i; while (a[i]<=a[l[i]-1]) l[i]=l[l[i]-1]; } FREE(i,n,1) { r[i]=i; while (a[i]<=a[r[i]+1]) r[i]=r[r[i]+1]; } ll ans=0; FRE(i,0,n) ans=max(ans,a[i]*(r[i]-l[i]+1)); pf("%lld\n",ans); } return 0; }
Largest Rectangle in a Histogram (poj 2559 && hdu 1506 矩形系列 迭代法)
原文地址:http://blog.csdn.net/u014422052/article/details/44455123