POJ2559 Largest Rectangle in a Histogram(单调栈)

题意:

给出一组矩形的高,求最多能拼成矩形的最大面积,看图就很清楚了。

要点:

还是单调栈,现在有点感觉了,单调栈大概就是能求出当前值左右的比它大或小的数的范围。这题用高度作为单调栈,分别往左右找比当前高度大的数的范围,最后求个面积即可。


15402130 Seasonal 2559 Accepted 1440K 157MS C++ 823B 2016-04-17 10:59:21
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define maxn 100005
int a[maxn],stack[maxn];
int l[maxn], r[maxn];

int main()
{
	int n, i, j,top;
	while (scanf("%d",&n)&&n)
	{
		for (int i = 1; i <= n; i++)
			scanf("%d", &a[i]);
		top = 0;
		for (i = 1; i <= n; i++)
		{
			while (top > 0 && a[stack[top - 1]] >= a[i])//寻找左边界
				top--;
			l[i] = top == 0 ? 1 : stack[top-1]+1;//如果大于栈顶,要+1来使左边界位于当前值,同样小于栈顶也要+1,因为栈顶肯定不能在边界内
			stack[top++] = i;
		}
		top = 0;
		for (i = n; i >= 1; i--)
		{
			while (top >0&&a[stack[top - 1]] >= a[i])//倒序寻找右边界
				top--;
			r[i] = top == 0 ? n : stack[top-1]-1;
			stack[top++] = i;
		}
		long long max = -1;
		for (i = 1; i <= n; i++)
			if (max < (long long)a[i] * (r[i] - l[i]+1))//边界之差要+1
				max = (long long)a[i] * (r[i] - l[i]+1);
		printf("%lld\n", max);
	}
	return 0;
}


posted @ 2016-04-17 11:18  seasonal  阅读(81)  评论(0编辑  收藏  举报