hdu 1506(单调栈实现)

本文介绍了一种使用栈来解决最大矩形面积问题的方法。通过遍历输入的高度数组,并利用栈来维护一个递增序列,可以高效地计算出包含每个柱状区域的最大矩形面积。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <iostream>
#include<stack>
#include<cstdio>
using namespace std;
struct node{
int w=1;
long long h;
}s[100005];
int main()
{
	int n;
while(scanf("%d",&n)!=EOF&&n)
{
	int i;
	stack<node>st;
	for(i=0;i<n;i++)
	{
		scanf("%lld",&s[i].h);
		s[i].w=1;//忘记重置为1导致错误
	}
	st.push(s[0]);
	long long total_w,cur_area,maxn=0;
	for(i=1;i<n;i++)
	{
		if(s[i].h>=s[i-1].h)//维护栈的单调增
		{
			st.push(s[i]);
		}
		else
		{
			total_w=0,cur_area=0;
			while(!st.empty()&&s[i].h<st.top().h)
			{
				total_w+=st.top().w;
				cur_area=total_w*st.top().h;//总宽*当前矩形的高度
				if(cur_area>maxn) maxn=cur_area;
				st.pop();//否则出栈
			}
			total_w+=s[i].w;//加上要进栈的矩形宽度
			s[i].w=total_w;//合并成新的矩形
			st.push(s[i]);
		}
	}
	total_w=0,cur_area=0;
	while(!st.empty())
	{
		total_w+=st.top().w;
		cur_area=total_w*st.top().h;
		if(cur_area>maxn) { maxn=cur_area;}
		st.pop();
	}
	printf("%lld\n",maxn);
}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值