【poj 2559】Largest Rectangle in a Histogram

http://poj.org/problem?id=2559

不是很难的题……大一的时候貌似就写过,但是思路忘了。这次是用单调栈写的。

题目大意:在一排的矩形中找出一个面积最大的能够覆盖连续矩形的大矩形,这个大矩形的高不超过被覆盖矩形的最矮的高。

(我还是不太懂记录刷过的题有什么用处。有很明显的帮助吗?能够帮你系统地归纳整理算法和心得?如果大牛们看到了请不吝赐教……)

对了,之前h数组是int,但是wa了,改成long long才对,因为tarea = h[i] * (r[i] - l[i] - 1)。此句中,右侧都是int类型,结果就算tarea是long long也没用。

/*
 * rectangle.cpp
 *  Created on: 2014年12月18日
 *      Author: Pan Hong
 */
/*
 * 方法:
 * 单调栈
 */
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>  //for memset
#include <algorithm>
#include <stack>
#define MAXN 100005
using namespace std;
long long int h[MAXN];//从1开始用
int l[MAXN], r[MAXN];
int main()
{
	int n;
	stack<int> pos;
	while(cin >> n && n)
	{
		pos.push(0);
		memset(l, 0, sizeof(l));
		memset(r, 0, sizeof(r));
		memset(h, 0, sizeof(h));
		h[0] = -1;
		for(int i = 1; i <= n; i++)
		{
			cin >> h[i];
			if(h[i] > h[pos.top()])//当前元素高度大于栈顶
			{
				l[i] = pos.top();//记录左侧第一个小于h[i]高度的位置
				pos.push(i);
			}
			else//小于等于栈顶
			{
				while(h[i] <= h[pos.top()])//直到栈顶小于h[i]
				{
					pos.pop();
				}
				l[i] = pos.top();
				pos.push(i);
			}
		}//输入树高,顺便求l数组.l数组内容可能是0,此时表示左边无更小的值了。
		while(!pos.empty())
		{
			pos.pop();
		}//清空栈
		h[n+1] = -1;
		pos.push(n+1);
		for(int i = n; i >= 1; i--)
		{
			if(h[i] > h[pos.top()])
			{
				r[i] = pos.top();
				pos.push(i);
			}
			else
			{
				while(h[i] <= h[pos.top()])
				{
					pos.pop();
				}//一直弹到栈顶小于当前高度
				r[i] = pos.top();
				pos.push(i);
			}
		}//计算r数组的内容
		long long int area = 0;
		long long int tarea;
		for(int i = 1; i <= n; i++)
		{
			tarea = h[i] * (r[i] - l[i] - 1);
			area = area > tarea ? area : tarea;
		}
		cout << area << endl;
	}
}


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值