poj1506(栈优化技巧)

来源:互联网 发布:minecraft模块编程 编辑:程序博客网 时间:2024/05/20 08:23


题意:给出一些柱状图,要求求出柱状图中长方形的最大面积。


思路:以每个点为起点,左右延伸,要保持a[j] >= a[i] ,a[j]为a[i]两边的数,得到以a[i]为高形成的长方形,底为满足a[j] >= a[i],经过i并且连续的区间。然后枚举以h[i]为高形成的长方形的面积的大小,得出答案。

这里得到以a[i] 为高的长方形的底的方法为:因为数有10^6个,所以不能暴力。

当算这个区间的最左端L[i]的时候,用一个栈维护每一段连续递减区间的最小值,也就是每一段连续递减区间的最右端的值。因为如果这个递减区间的最小值大于a[i]的话,那么这个递减区间都大于a[i]了。

同理,可以算出最右端R[i]。


#include<bits/stdc++.h>using namespace std;const int maxn = 100000 + 10;typedef long long ll;int n;int a[maxn];int L[maxn],R[maxn];int st[maxn];int main(){    while( ~ scanf("%d",&n) && n)    {        for(int i = 1; i <= n; i ++)            scanf("%d",&a[i]);        int top = 0;        for(int i = 1; i <= n; i ++)        {            while(top && a[st[top]] >= a[i])                top --;            L[i] = (top == 0) ? 1 : st[top] + 1;            st[++ top] = i;        }        top = 0;        for(int i = n; i >= 1; i --)        {            while(top && a[st[top]] >= a[i])                top --;            R[i] = (top == 0) ? n : st[top] - 1;            st[++ top] = i;        }        ll ans = 0;        for(int i = 1; i <= n; i ++)        {//            cout << i << " " << L[i] << " " << R[i] << endl;            ans = max(ans,(ll)a[i] * (ll)(R[i] - L[i] + 1));        }        printf("%I64d\n",ans);    }    return 0;}


原创粉丝点击