Largest Rectangle in a Histogram (POJ - 2559,单调栈入门题)

本文介绍了一道经典的算法题——使用单调栈求解由多个矩形组成的最大面积问题。通过单调栈来高效地找到每个高度对应的最优宽度,从而得到最大的矩形面积。

一.题目链接:

POJ-2559

二.题目大意:

有 n 个长方形排在一条线上,宽均为 1 ,给出每个矩形的高度.

用一个长方形木板截取,求截得的最大面积.

三.分析:

沙比题,分析个毛,单调栈入门题.

好的,就这样.

四.代码实现:

#include <set>
#include <map>
#include <ctime>
#include <queue>
#include <cmath>
#include <stack>
#include <vector>
#include <cstdio>
#include <sstream>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#define eps 1e-6
#define pi acos(-1.0)
#define ll long long int
using namespace std;
const int M = (int)1e5;
const ll mod = (ll)1e9 + 7;
const ll inf = 0x3f3f3f3f3f;

ll height[M + 5];
ll st[M + 5];
ll width[M + 5];

int main()
{
    int n;
    while(~scanf("%d", &n) && n)
    {
        for(int i = 1; i <= n; ++i)
            scanf("%lld", &height[i]);
        height[n + 1] = 0;
        ll ans = 0;
        int top = 0;
        for(int i = 1; i <= n + 1; ++i)
        {
            if(height[i] > st[top])
            {
                st[++top] = height[i];
                width[top] = 1;
            }
            else
            {
                int w = 0;
                while(height[i] < st[top])
                {
                    w += width[top];
                    ans = max(ans, st[top] * w);
                    top--;
                }
                st[++top] = height[i];
                width[top] = w + 1;
            }
        }
        printf("%lld\n", ans);
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值