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.

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 <i>n</i>, denoting the number of rectangles it is composed of. You may assume that <i>1<=n<=100000</i>. Then follow <i>n</i> integers <i>h<sub>1</sub>,...,h<sub>n</sub></i>,
where <i>0<=h<sub>i</sub><=1000000000</i>. These numbers denote the heights of the rectangles of the histogram in left-to-right order. The width of each rectangle is <i>1</i>. 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
求最大面积,想了好长时间。
如果常规的来做的话,依次遍历所有的柱子,在某一个柱子的时候要 向左扩展,向右扩展,看看高于等于当前柱子的个数有几个,这又要遍历一次。
很显然这样做的话TLE;
用这种思想来用栈做,左右扩展到达边界的下标。
#if 0
#include<iostream>
#include<stdio.h>
using namespace std;
const int Max=100000+10;
unsigned long long int a[Max],l[Max],r[Max],q[Max];
int main()
{
int n;
while(scanf("%d",&n))
{
if(n==0)
break;
for(int i=1; i<=n; i++)
{
scanf("%I64d",&a[i]);
l[i]=r[i]=i;
}
int t=0;
for(int i=1; i<=n; i++)
{
while(t&&a[i]<=a[q[t]]) //下降
t--;
if(t==0)
l[i]=1;
else
l[i]=q[t]+1;
q[++t]=i;
}
t=0;
for(int i=n; i>=1; i--)
{
while(t&&a[i]<=a[q[t]])
t--;
if(t==0)
{
r[i]=n;
}
else
{
r[i]=q[t]-1;
}
q[++t]=i;
}
unsigned long long int maxx=0;
for(int i=1; i<=n; i++)
{
unsigned long long int temp=(r[i]-l[i]+1)*a[i];
if(maxx<temp)
maxx=temp;
}
printf("%I64d\n",maxx);
}
}
#endif
本文介绍了一种高效算法,用于解决寻找直方图中最大矩形面积的问题。该算法通过两次遍历直方图,利用栈记录每个矩形左侧和右侧最近的小于当前高度的位置,从而避免了多次重复计算,显著提高了计算效率。
450

被折叠的 条评论
为什么被折叠?



