解题报告 『HISTOGRA - Largest Rectangle in a Histogram(单调栈)』

Posted kirisame-marisa

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了解题报告 『HISTOGRA - Largest Rectangle in a Histogram(单调栈)』相关的知识,希望对你有一定的参考价值。

原题地址

单调栈板子题,代码很简单。

注意将a[n + 1]赋值为0,防止栈中矩形未弹完。

 

代码实现如下:

技术图片
#include <bits/stdc++.h>
using namespace std;
#define LL long long
#define rep(i, a, b) for (register int i = a; i <= b; i++)

const int maxn = 1e5 + 5;

int n;
int a[maxn], sta[maxn], wid[maxn];

LL MAX(LL a, LL b) return a > b ? a : b;

void origin() memset(sta, 0, sizeof(sta));

int main() 
    std::ios::sync_with_stdio(false);
    std::cin.tie(0);
    while (cin >> n && n) 
        origin();
        rep(i, 1, n) cin >> a[i];
        int p = a[n + 1] = 0;
        LL ans = 0;
        rep(i, 1, n + 1) 
            if (a[i] > sta[p]) 
                sta[++p] = a[i];
                wid[p] = 1;
            
            else 
                int width = 0;
                while (a[i] < sta[p]) 
                    width += wid[p];
                    ans = MAX(ans, (LL)width * sta[p]);
                    p--;
                
                sta[++p] = a[i], wid[p] = width + 1;
            
        
        cout << ans << endl;
    
    return 0;
View Code

以上是关于解题报告 『HISTOGRA - Largest Rectangle in a Histogram(单调栈)』的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode --- 976. Largest Perimeter Triangle 解题报告

LeetCode --- 1399. Count Largest Group 解题报告

LeetCode --- 1624. Largest Substring Between Two Equal Characters 解题报告

LeetCode --- 1624. Largest Substring Between Two Equal Characters 解题报告

LeetCode --- 1624. Largest Substring Between Two Equal Characters 解题报告

题解报告:poj 2559 Largest Rectangle in a Histogram(单调栈)