Largest Rectangle in a Histogram POJ - 2559 (单调栈)

本文介绍了一种使用C++编程语言解决POJ-2559问题的方法,通过栈和pair数据结构进行高效计算,实现了对输入数据的有效处理和最大值的快速求解。

https://cn.vjudge.net/problem/POJ-2559

#include <iostream>
#include <algorithm>
#include<stack>
using namespace std;
#define ll long long
typedef pair<ll,ll> pll;
stack<pll> s;
int main()
{
    ll n,m,i,j,ans,x;
    while(scanf("%lld",&n) != EOF&&n){
    ll MAX = 0;
    for(i=1;i<=n;i++)
    {
        scanf("%lld",&x);
        ll w = 0;
        while(!s.empty()&&s.top().first >= x)
        {
            ll tmph = s.top().first;
            ll tmpw = s.top().second;
            s.pop();
            w += tmpw;
            MAX = max(MAX,tmph*w);
        }
        s.push(make_pair(x,w+1));
    }
    int tmp = 0;
    while(!s.empty())
    {
        MAX = max(MAX,s.top().first*(tmp+s.top().second));
        tmp += s.top().second;
        s.pop();
    }
    printf("%lld\n",MAX);
    }
    return 0;
}

 

### 关于直方图中最大矩形积的算法 要解决直方图中的最大矩形积问题,可以采用一种基于单调栈的方法来实现效的解决方案。这种方法的时间复杂度为 \(O(n)\),其中 \(n\) 是输入数组的度数量。 以下是解决问题的核心思路: 1. 使用一个栈存储柱状图的索引。 2. 遍历整个度数组,在遍历时维护一个递增顺序的栈。 3. 当遇到当前度小于等于栈顶对应的度时,弹出栈顶并计算以该度为基础的最大矩形积[^1]。 4. 如果栈为空,则度为当前索引;如果栈不为空,则度为当前索引减去新的栈顶索引再减一[^2]。 5. 继续处理直到完成所有元素的扫描,并清空栈以确保所有可能的矩形都被考虑[^3]。 #### Python 实现代码 下是一个完整的 Python 实现方案: ```python def largest_rectangle_area(heights): stack = [] max_area = 0 index = 0 while index < len(heights): if not stack or heights[index] >= heights[stack[-1]]: stack.append(index) index += 1 else: top_of_stack = stack.pop() width = index if not stack else index - stack[-1] - 1 max_area = max(max_area, heights[top_of_stack] * width) while stack: top_of_stack = stack.pop() width = index if not stack else index - stack[-1] - 1 max_area = max(max_area, heights[top_of_stack] * width) return max_area ``` 这段代码通过不断调整栈的状态以及利用度和度的关系,能够效地找到最大矩形积[^4]。 #### C++ 实现代码 这里也提供了一个类似的 C++ 版本实现: ```cpp #include <iostream> #include <stack> #include <vector> using namespace std; int largestRectangleArea(vector<int>& heights) { stack<int> st; int maxA = 0; int n = heights.size(); for(int i = 0; i <= n; ++i){ int h = (i == n ? 0 : heights[i]); if(st.empty() || h >= heights[st.top()]) st.push(i); else{ int tp = st.top(); st.pop(); maxA = max(maxA, heights[tp]*(st.empty()?i:(i-st.top()-1))); --i; } } return maxA; } int main(){ vector<int> height = {2, 1, 5, 6, 2, 3}; cout << "The largest Rectangle in histogram is " << largestRectangleArea(height) << endl; } ``` 此版本同样遵循相同的逻辑框架,但在细节上略有不同以便更好地适应C++语法特点[^5]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值