题目链接:点击进入
题目


题意
n 个矩形,连在一起,按顺序给出每个矩形的高度 h [ i ] ,宽度都为 1 ,问能形成的最大矩形面积为多少。
思路
单调栈维护一个递减的序列,存储的是代表元素的位置,栈空或者元素大于等于栈顶元素则入栈,否则,栈顶出栈,直至栈空或者遇到栈顶元素小于等于枚举的元素,出栈过程中,更新以出栈栈顶元素为最低高度的,且以栈顶元素位置为左边界、以枚举元素为右边界所形成的最大矩形面积。出栈结束后,将最后一次出栈的栈顶位置入栈,同时更新此位置元素为枚举元素( 表示以枚举元素为最低元素时,左边界最远可到这个位置 )。
代码
#include<iostream>
#include<string>
#include<map>
#include<set>
//#include<unordered_map>
#include<queue>
#include<cstdio>
#include<vector>
#include<cstring>
#include<stack>
#include<algorithm>
#include<iomanip>
#include<cmath>
#include<fstream>
#define X first
#define Y second
#define best 131
#define INF 0x3f3f3f3f3f3f3f3f
#define pii pair<int,int>
#define lowbit(x) x & -x
#define inf 0x3f3f3f3f
//#define int long long
//#define double long double
//#define rep(i,x,y) for(register int i = x; i <= y;++i)
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const double pai=acos(-1.0);
const int maxn=1e8+10;
const int mod=998244353;
const double eps=1e-9;
const int N=5e3+10;
//inline int read()
//{
// int k = 0, f = 1 ;
// char c = getchar() ;
// while(!isdigit(c)){if(c == '-') f = -1 ;c = getchar() ;}
// while(isdigit(c)) k = (k << 1) + (k << 3) + c - 48 ,c = getchar() ;
// return k * f ;
//}
ll t,n,m,ans,top,a[maxn];
stack<int>st;
int main()
{
while(cin>>n)
{
if(n==0) break;
for(int i=1;i<=n;i++)
cin>>a[i];
ll ans=0;a[n+1]=-1;
for(int i=1;i<=n+1;i++)
{
if(st.empty()||a[i]>=a[st.top()])
st.push(i);
else
{
while(st.size()&&a[i]<a[st.top()])
{
top=st.top();
st.pop();
ll tmp=(i-top)*a[top];
ans=max(ans,tmp);
}
st.push(top);
a[top]=a[i];
}
}
cout<<ans<<endl;
}
return 0;
}
单调栈解决最大矩形面积问题
该博客主要介绍了一种使用单调栈解决求解一组矩形高度中能形成的最大矩形面积的问题。通过维护一个递减的栈,存储矩形高度的位置,当遇到高度大于等于栈顶高度的矩形时入栈,否则不断出栈并更新最大矩形面积。最后输出最大面积。
445

被折叠的 条评论
为什么被折叠?



