题目
在一条水平线上方有若干个矩形,求这些矩形的并集中最大矩形的面积。

分析
这道题目可以用单调栈的,维护一个单调递增的栈,从左到右枚举每一个矩形,如果当前矩形比栈顶高,直接入队,否则不断取出栈顶,直到栈为空或当前矩形比栈顶高,在出栈时,不断累计矩形的宽度,累计答案,并把最后的矩形入栈。
代码
#include <cstdio>
#include <stack>
#include <cstring>
using namespace std;
int n,a[100001],w[100001]; long long ans; stack<int>st;
int main(){
while (1){
scanf("%d",&n); ans=0;
if (n==0) return 0; memset(w,0,sizeof(w));
for (int i=1;i<=n;i++) scanf("%d",&a[i]);
while (st.size()) st.pop(); a[n+1]=0;
for (int i=1;i<=n+1;i++){
if (st.size()&&a[i]>a[st.top()]) st.push(i),w[st.top()]=1;
else{
int width=0;
while (st.size()&&a[st.top()]>a[i]){
width+=w[st.top()];
ans=max(ans,(long long)width*a[st.top()]);
st.pop();
}
st.push(i); w[st.top()]=width+1;
}
}
printf("%lld\n",ans);
}
}
本文介绍了一种使用单调栈解决多个矩形并集内最大矩形面积问题的算法。通过维护一个单调递增栈,从左到右遍历每个矩形,确保能够有效地计算出最大矩形面积。
344

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



