单调栈的运用

本文介绍了一种使用单调栈解决寻找直方图中最大矩形面积问题的算法,并提供了完整的AC代码实现。
E - E
Time Limit:1000MS    Memory Limit:131072KB    64bit IO Format:%lld & %llu

Description

Given n positive integers representing the histogram's bar height where the width of each bar is 1, find the area of largest rectangle in the histogram.

Above is a histogram where width of each bar is 1, given height =[2,1,5,6,2,3].

The largest rectangle is shown in the shaded area, which has area = 10 unit.

Input

  The first line of the input file contains an integer T (T<=100) specifying the number of test cases.
Each test case begins with a line containing an integer N (1<=N<=100000),The following N-1 lines each contain a integer A[i](1<=A[i]<=10000).

Output

 For each query, output a single line containing largest area. 

Sample Input

2
6
2
1
5
6
2
3
10
1
2
3
4
5
6
7
9
10
8

Sample Output

10
30

题解: 单调栈

AC代码:

#include <iostream>
#include <stdio.h>
#include <stack>
#include <algorithm>
using namespace std;

typedef long long ll;
typedef pair<int,int> P;
const int M = 1e5 + 5;
stack<P> st;
int a[M],L[M],R[M],N;

void solve(int c[],int val) {
    while(st.size()) st.pop();
    for(int i = 1; i <= N + 1; i++) {
        int x = a[i];
        while(!st.empty() && st.top().first > x) {
            if(val) c[st.top().second] = (i - st.top().second) * st.top().first;
            else c[N - st.top().second + 1] = (i - st.top().second) * st.top().first;
            st.pop();
        }
        st.push(make_pair(x,i));
    }
}

int main() {
    int T;
    cin>>T;
    while(T--) {
        while(st.size() > 0) st.pop();
        int ans = 0;
        scanf("%d",&N);
        for(int i = 1; i <= N; i++) {
            scanf("%d",&a[i]);
        }
        a[N + 1] = 0;
        solve(R,1);
        reverse(a + 1,a + N + 1);
        solve(L,0);
        reverse(a + 1,a + N + 1);
        for(int i = 1; i <= N; i++) ans = max(ans,L[i] + R[i] - a[i]);
        printf("%d\n",ans);
    }
    return 0;
}

### 单调栈算法简介 单调栈是一种特殊的结构,在处理某些特定问题时非常高效。其核心特点是保持内元素按照某种顺序排列,通常为递增或递减序列[^1]。 #### 单调栈应用场景 当遇到如下特征的问题时可以考虑使用单调栈: - 需要找到某个范围内最大/最小值的位置 - 寻找左侧第一个大于等于当前数的位置 - 查找右侧第一个小于当前位置数值的情况 这些问题在实际编程竞赛中较为常见,尤其是在涉及数组、链表等线性数据结构的操作上表现出色[^2]。 #### AcWing平台上的单调栈题目实例解析 ##### 实例一:寻找下一个更大元素 (Next Greater Element) 给定两个没有重复数字的数组 `nums1` 和 `nums2` ,其中 `nums1` 是 `nums2` 的子集。对于每一个位于 `nums1[i]` 中的元素,在 `nums2` 数组里查找该位置右边的第一个更大的数;如果不存在,则返回 `-1` 。此题可以通过构建一个从右向左遍历并维护降序关系的单调栈来解决。 ```python def nextGreaterElement(nums1, nums2): stack = [] res_map = {} for num in reversed(nums2): while stack and stack[-1] <= num: stack.pop() if not stack: res_map[num] = -1 else: res_map[num] = stack[-1] stack.append(num) result = [res_map[x] for x in nums1] return result ``` 上述代码实现了通过一次反向扫描建立映射表的功能,并利用了单调栈特性快速定位到目标值及其对应的最近较大值[^3]。 ##### 实例二:柱状图中的最大矩形面积 (Largest Rectangle in Histogram) 这个问题要求在一个由多个宽度相同但高度不同的直方条组成的图形中找出能够构成的最大矩形区域。解决方案之一就是采用两次正逆双向遍历的方法配合单调栈实现高效的计算过程。 ```python def largestRectangleArea(heights): heights.append(0) # 添加哨兵节点简化边界条件判断 stack = [-1] max_area = 0 for i, h in enumerate(heights): while heights[stack[-1]] > h: height = heights[stack.pop()] width = i - stack[-1] - 1 max_area = max(max_area, height * width) stack.append(i) return max_area ``` 这段程序展示了如何巧妙运用单调栈技巧以及额外加入辅助元素的方式解决了复杂度较高的几何优化难题[^4]。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值