HDU1506 Largest Rectangle in a Histogram (单调栈)

题目链接: Largest Rectangle in a Histogram

大致题意

给定一个宽度为 n n n的图形, 由 n n n个宽度为1, 高度为 h i h_i hi的矩形组成.

要求计算出最大矩形的面积.

解题思路

思维

首先我们最终选取出的大矩形高度一定为某个 h i h_i hi.

我们考虑到对于完全包含第 i i i个小矩形而言的答案, 相当于需要在 i i i左侧找到小于 h i h_i hi的点, 则记录 i i i位置可以向左延伸 l i l_i li, 右侧同理记录出 r i r_i ri.

这样答案为 r e s = m a x ( ( r i − l i − 1 ) × h i ) res = max({ (r_i - l_i - 1) \times h_i }) res=max((rili1)×hi).

单调栈

由于我们需要计算出某个位置左侧第一个小于 h i h_i hi的点, 因此可以采用单调栈维护.

AC代码

#include <bits/stdc++.h>
#define rep(i, n) for (int i = 1; i <= (n); ++i)
using namespace std;
typedef long long ll;
const int N = 1E5 + 10;
int a[N], l[N], r[N];
int main()
{
	int n;
	while (scanf("%d", &n), n) {
		rep(i, n) scanf("%d", &a[i]);

		stack<int> st;
		rep(i, n) {
			while (!st.empty() and a[st.top()] >= a[i]) st.pop();
			l[i] = st.empty() ? i : i - st.top();
			st.push(i);
		}

		st = stack<int>();
		for (int i = n; i >= 1; --i) {
			while (!st.empty() and a[st.top()] >= a[i]) st.pop();
			r[i] = st.empty() ? n - i + 1 : st.top() - i;
			st.push(i);
		}

		ll res = 0;
		rep(i, n) res = max(res, 1ll * (r[i] + l[i] - 1) * a[i]);

		printf("%lld\n", res);
	}

	return 0;
}

END

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

逍遥Fau

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值