【POJ】2559 Largest Rectangle in a Histogram

【POJ】2559 Largest Rectangle in a Histogram

Time Limit: 1000MS
Memory Limit: 65536K

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.

翻译

直方图中最大的矩形

时限: 1000MS
内存限制: 65536K

描述

直方图是由在公共基准线上对齐的一系列矩形组成的多边形。矩形的宽度相等,但高度可以不同。例如,左图显示了直方图,该直方图由高度为2、1、4、5、1、3、3的矩形组成,以单位为单位,其中1是矩形的宽度:

通常,直方图用于表示离散分布,例如,文本中字符的频率。注意,矩形的顺序,即它们的高度,很重要。计算直方图中与公共基线对齐的最大矩形的面积。右图显示了所描绘的直方图的最大对齐矩形。

输入

输入包含几个测试用例。每个测试用例都描述一个直方图,并以整数n开头,表示它所组成的矩形数。您可以假设1 <= n <= 100000。然后跟随n个整数h 1,…,h n,其中0 <= h i <= 1000000000。这些数字表示从左到右顺序的直方图矩形的高度。每个矩形的宽度为1。在最后一个测试用例的输入之后为零。

输出

对于单行上的每个测试用例输出,指定直方图中最大矩形的面积。请记住,此矩形必须与公共基准线对齐。

样本输入

7 2 1 4 5 1 3 3
4 1000 1000 1000 1000
0

样本输出

8
4000

暗示

大量输入,建议使用scanf。

思路

用单调栈做。
保存宽度。
找到大于当前高度的位置。
宽度加上他们的宽度。
计算面积,比较最大值。
删除大于当前数的数。
加入当前位置的高度和宽度。

代码

#include<iostream>
#include<cstdio>
#include<stack>
using namespace std;
long long a[100010]; 
struct jgt
{
    
    
	long long wide,high;//宽,高。 
}; 
stack<jgt> s;
int main()
{
    
    
	long long n,i,ans,w;
	jgt tem;
	for(scanf("%lld",&n);n;scanf("%lld",&n))
	{
    
    
		for(ans=0,i=1;i<=n;i++)
			scanf("%lld",&a[i]);
		a[n+1]=-1;
		for(i=1;i<=n+1;i++)
		{
    
    
			for(w=0;!s.empty()&&a[i]<=s.top().high;s.pop())//删除大于当前数的数
			{
    
    
			    w+=s.top().wide;//宽度增加 
			    ans=max(w*s.top().high,ans);//求最大面积 
			}
			tem.high=a[i],tem.wide=w+1;
			s.push(tem);
		}
		printf("%lld\n",ans);
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_46975572/article/details/114598292
今日推荐