hdu 1506 Largest Rectangle in a Histogram

Problem Description

A histogram is apolygon composed of a sequence of rectangles aligned at a common base line. Therectangles have equal widths but may have different heights. For example, thefigure on the left shows the histogram that consists of rectangles with the heights2, 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., thefrequencies of characters in texts. Note that the order of the rectangles,i.e., their heights, is important. Calculate the area of the largest rectanglein a histogram that is aligned at the common base line, too. The figure on theright shows the largest aligned rectangle for the depicted histogram.

 

 

Input

The input containsseveral test cases. Each test case describes a histogram and starts with aninteger n, denoting the number of rectangles it is composed of. You may assumethat 1 <= n <= 100000. Then follow n integers h1, ..., hn, where 0 <=hi <= 1000000000. These numbers denote the heights of the rectangles of thehistogram in left-to-right order. The width of each rectangle is 1. A zerofollows the input for the last test case.

 

 

Output

For each test caseoutput on a single line the area of the largest rectangle in the specifiedhistogram. Remember that this rectangle must be aligned at the common baseline.

 

 

Sample Input

7 2 1 4 5 1 3 3

4 1000 1000 10001000

0

 

 

Sample Output

8

4000

 求最大的矩阵。先从左到右,算出自己的左边比自己高度小的位置。然后再从右往左,同样。然后用右边界-左边界乘上自己的高度,就是以该高度为宽的最大矩阵。这里有一个小小的优化,不用一个一个去找。以找左边边界为例。如果k=i,num[k-1]>=num[i],那么,就直接到k-1的左边界,即left[k-1],然后再去找。因为如果num[k-1]>=num[i],那么left[k-1]到k-1一定也在这个矩阵之中了。

k-1#include<cstdio>
#include<cstring>
#include<cstdlib>
#define MAX 100010
#define LL long long
using namespace std;

LL num[MAX];
LL left[MAX] ,right[MAX];
LL ans;

int main()
{
	int n ,k;
	while(scanf("%d",&n),n)
	{
		ans = 0;
		for(int i = 0;i < n;i++)
		{
			scanf("%I64d",&num[i]);
		}
		for(int i = 0;i < n;i++)
		{
			k = i;
			while(k > 0 && num[k - 1] >= num[i])
			{
				k = left[k - 1];
			}
			left[i] = k;
		}
		for(int i = n-1;i >= 0;i--)
		{
			k = i;
			while(k < n - 1 && num[k + 1] >= num[i])
			{
				k = right[k + 1];
			}
			right[i] = k;
			if(ans < (right[i] - left[i] + 1) * num[i])
			{
				ans = (right[i] - left[i] + 1) * num[i];
			}
		}
		printf("%I64d\n",ans);
	}
	return 0;
}


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值