POJ2559Largest Rectangle in a Histogram 单调栈

题目

A histogram is a polygon composed of a sequence of rectangles aligned at a common base line. The rectangles have equal widths but may have different heights. For example, the figure on the left shows the histogram that consists of rectangles with the heights 2, 1, 4, 5, 1, 3, 3, measured in units where 1 is the width of the rectangles:
这里写图片描述
Usually, histograms are used to represent discrete distributions, e.g., the frequencies of characters in texts. Note that the order of the rectangles, i.e., their heights, is important. Calculate the area of the largest rectangle in a histogram that is aligned at the common base line, too. The figure on the right shows the largest aligned rectangle for the depicted histogram.
如下图所示,在一条水平线上方有若干个矩形,求包含于这些矩形的并集内部的最大矩形的面积(在下图中,答案就是阴影部分的面积),矩形个数<=10^5。

题解

多组数据
记得开long long+输出用%lld!!

用一个单调递增栈保存矩形高度,若加入的矩形高度小于栈顶高度,就弹出栈顶元素,累计弹出的矩形宽度,与每个弹出的矩形自身高度相乘更新答案,直到有矩形高度大于加入的矩形或栈空了,最后将加入的矩形与已经弹出的矩形合并成高度为加入矩形高度、宽度为累计宽度+1的矩形

代码

#include <cstdio>
#include <cstring>
#include <algorithm>

using namespace std;

int n,p;
long long ans;
int a[100005],b[100005];

int main(){
    scanf("%d",&n);
    while (n){
        memset(a,0,sizeof(a));
        memset(b,0,sizeof(b));
        ans=p=0;
        n++;
        while (n--){
            int x;
            if (n==0) x=0; else
            scanf("%d",&x);
            if (a[p]<x){ 
                a[++p]=x;b[p]=1;
            } else{
                int i=0;
                while (p&&a[p]>=x){
                    i+=b[p];
                    ans=max(ans,(long long)a[p]*i);
                    p--;
                }
                a[++p]=x;b[p]=i+1;
            }
        }
        printf("%lld\n",ans);
        scanf("%d",&n);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值