码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2019-07-15 17:21:41      阅读:101      评论:0      收藏:0      [点我收藏+]

标签:c++   blank   for   pac   return   get   src   报告   tar   

原题地址

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

注意将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(单调栈)』

标签:c++   blank   for   pac   return   get   src   报告   tar   

原文地址:https://www.cnblogs.com/Kirisame-Marisa/p/11189989.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!