HDU-1506 Largest Rectangle in a Histogram

本文介绍了一种使用单调栈解决最大矩形问题的方法。通过维护一个单调递增的栈,栈中元素为高度和位置的二元组,实现了在数组中寻找以每个柱子为最小高度的最大矩形面积。代码示例展示了如何在遍历过程中更新并找到全局最大值。

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

题目来源:http://acm.hdu.edu.cn/showproblem.php?pid=1506

单调栈STL写法。

维护一个单调递增的单调栈,栈中元素为二元组(h,pos),h为第一关键字。弹出栈时更新最大值。

代码:

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
#include <queue>
#include <stack>
#include <map>
#include <set>

#define ll long long
#define ull unsigned long long
#define BUG cout<<"*************************"<<endl
using namespace std;

const ll mod = 998244353;
const int maxn = 1e5 + 10;
const int maxm = 1e6 + 10000;
const double eps = 1e-8;

stack<pair<ll, ll> > s;
ll n, a[maxn];

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    while (cin >> n) {
        if (n == 0)break;
        for (int i = 1; i <= n; ++i) {
            cin >> a[i];
        }
        ll ans = 0;
        for (ll i = 1; i <= n; ++i) {
            while (!s.empty() && s.top().first > a[i]) {
                pair<ll, ll> p = s.top();
                s.pop();
                if (s.empty()) {
                    ans = max(ans, p.first * (i - 1));
                }
                else {
                    ans = max(ans, (i - 1 - s.top().second) * p.first);
                }
            }
            s.push(pair<int, int>(a[i], i));
        }
        while (!s.empty()) {
            pair<ll, ll> p = s.top();
            s.pop();
            if (s.empty()) {
                ans = max(ans, n * p.first);
            }
            else {
                ans = max(ans, (n - s.top().second) * p.first);
            }
        }
        cout << ans << endl;
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值