51nod 1102

来源:互联网 发布:网上购物商城源码ssh 编辑:程序博客网 时间:2024/06/06 15:53

题目大意:

有一个正整数的数组,化为直方图,求此直方图包含的最大矩形面积。例如 2,1,5,6,2,3,对应的直方图如下:


面积最大的矩形为5,6组成的宽度为2的矩形,面积为10。
Input
第1行:1个数N,表示数组的长度(0 <= N <= 50000)第2 - N + 1行:数组元素A[i]。(1 <= A[i] <= 10^9)
Output
输出最大的矩形面积
Input示例
6215623
Output示例
10

基本思路:

单调栈不多说,然后就是正反各来一次维护,我感觉这样好写;

代码如下:

#include<iostream>
#include<iomanip>
#include<algorithm>
#include<string>
#include<queue>
#include<vector>
#include<list>
#include<stack>
#include<map>
#include<set>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<cstdlib>


using namespace std;


const int inf = 0x3f3f3f3f;
const int maxn = 50000+10;
typedef pair<int,int> pii;
typedef long long int ll;
int l[maxn],r[maxn];
int ans[maxn];


int main()
{
    int n;
    scanf("%d",&n);
    for(int i=1;i<=n;i++) scanf("%d",&ans[i]);
    stack<int> s1,s2;
    for(int i=1;i<=n;i++)
    {
        while(!s1.empty()&&ans[s1.top()]>=ans[i]) s1.pop();
        if(s1.empty()) l[i]=1;
        else l[i]=s1.top()+1;//然后这里直接这样不是自己想的那样的原因就是这个大于等于是有传递性的,需要好好理解;
        s1.push(i);
    }
    for(int i=n;i>=1;i--)
    {
        while(!s2.empty()&&ans[s2.top()]>=ans[i]) s2.pop();
        if(s2.empty()) r[i]=n;
        else r[i]=s2.top()-1;
        s2.push(i);
    }
    ll maxx=-inf;
    for(int i=1;i<=n;i++)
    maxx=max(maxx,(r[i]-l[i]+1)*(ll)ans[i]);
    printf("%I64d\n",maxx);
    return 0;
}