单调栈及其应用

单调栈

#include <iostream>
#include <vector>
#include <stack>

// 直方图最大矩形面积
int MaxMatrixArea(const std::vector<int>& line) {
    if (line.empty()) {
        return 0;
    }
    std::stack<int> st;
    int maxArea = 0;
    for (int i = 0; i < line.size(); i++) {
        while (!st.empty() && line[st.top()] <= line[i]) {
            int t = st.top();
            int area = (i - t) * line[t];  // 底 * 高 = 面积
            if (area > maxArea) {
                maxArea = area;
            }
            st.pop();
        }
        st.push(i);  // 存储的是下标
    }
    int n = line.size();
    while (!st.empty()) {  // 处理栈中剩余的元素
        int t = st.top();
        int area = (n - t) * line[t];
        if (area > maxArea) {
            maxArea = area;
        }
        st.pop();
    }
    return maxArea;
}

// 矩阵等效转换直方图
int MaxSubMatrix(const std::vector<std::vector<int>>& mat) {
    if (mat.empty()) {
        return 0;
    }
    int H = mat.size();
    int L = mat[0].size();
    std::vector<int> heigh(mat[0].size(), 0);
    for (int j = 0; j < L; ++j) {  // 初始化第一行
        heigh[j] = mat[0][j];
    }
    int maxSize = MaxMatrixArea(heigh);
    for (int i = 1; i < H; ++i) {
        for (int j = 0; j < L; ++j) {  // 递推累加
            heigh[j] = (mat[i][j] == 0) ? 0 : heigh[j] + 1;
        }
        int size = MaxMatrixArea(heigh);  // 每行相对于之前的行都是递推来的数值
        if (size > maxSize) {
            maxSize = size;
        }
    }
    return maxSize;
}

int main() {
    std::vector<int> line {3, 2, 3, 0};
    int res = MaxMatrixArea(line);
    std::cout << "result = " << res << std::endl;
    std::vector<std::vector<int>> mat = {
        {1, 0, 1, 1}, 
        {1, 1, 1, 1}, 
        {1, 1, 1, 0}};
    res = MaxSubMatrix(mat);
    std::cout << "max matrix area = " << res << std::endl;
    return 0;
}

参考资料

  • https://blog.csdn.net/roufoo/article/details/78569554
  • https://blog.csdn.net/yutianzuijin/article/details/52072427
  • https://www.cnblogs.com/grandyang/p/8887985.html
  • https://oi-wiki.org/ds/monotonous-stack/
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值