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

POJ 2559 - Largest Rectangle in a Histogram - [单调栈]

时间:2018-11-04 21:23:17      阅读:151      评论:0      收藏:0      [点我收藏+]

标签:矩形   pop   pre   stack   target   typedef   c代码   push   pair   

题目链接:http://poj.org/problem?id=2559

 

题意:

给出 $n(1 \le n \le 10^5)$ 个宽为 $1$,高为 $h_i(0 \le h_i \le 10^9)$ 的矩形,它们从原点开始并排在 $x$ 轴上,

现在要求出,这个合并产生的图形内部最大的矩形的面积。

 

Sample Input

7 2 1 4 5 1 3 3

4 1000 1000 1000 1000

0

 

Sample Output

8

4000

 

题解:

如果矩形的高度从左到右是单增的,那么答案必然是尝试每个矩形的高度作为答案矩形的高度,而宽度则一直延伸到右边界。

如果出现了某个矩形,其高度比上一个矩形小,那么可想而知,此前那些矩形往右延伸遇到了当前这个矩形,高度必然要被压低,

换句说,再往后,答案矩形的高度就受制于当前矩形而非前面那些矩形了。因此,可以将前面所有高过我的矩形统统变成跟我一样高的。

这样一来,栈内维护的矩形高度永远是单增的。

 

AC代码:

#include<iostream>
#include<cstdio>
#include<stack>
#include<algorithm>
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
const int maxn=100000+10;

int n,h[maxn];
stack<pii> S;
int main()
{
    while(scanf("%d",&n) && n)
    {
        for(int i=1;i<=n;i++) scanf("%d",&h[i]);
        ll ans=0;
        for(int i=1;i<=n;i++)
        {
            if(S.empty() || h[i]>=S.top().first) {
                S.push(make_pair(h[i],1));
            } else {
                int w=0;
                while(S.size() && h[i]<S.top().first)
                {
                    w+=S.top().second;
                    ans=max(ans,(ll)w*S.top().first);
                    S.pop();
                }
                S.push(make_pair(h[i],w+1));
            }
        }
        int w=0;
        while(!S.empty())
        {
            w+=S.top().second;
            ans=max(ans,(ll)w*S.top().first);
            S.pop();
        }
        printf("%I64d\n",ans);
    }
}

 

POJ 2559 - Largest Rectangle in a Histogram - [单调栈]

标签:矩形   pop   pre   stack   target   typedef   c代码   push   pair   

原文地址:https://www.cnblogs.com/dilthey/p/9905428.html

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