hdu 1506 Largest Rectangle in a Histogram

DP

http://acm.hdu.edu.cn/showproblem.php?pid=1506

思路就是记录下每个点大于等于他的最左边和最右边的位置就能够计算了
暴力地去找肯定不行,关键就是优化
比如找 L [ i ] 的时候, L 是记录左边的东西,因此要是 L [ i ] 左边的就全部是已知的东西,那就能够往右边推,右边一个的信息就能够很快地由已知信息得到
同理,求 R 的时候就从右往左推

而且这种记录这个点左右信息的思维很牛逼的,以前有道切玻璃的题,然后要倒着来把玻璃拼回去就是用的这种思想,还有舞蹈链也是有这种思想~

#include"iostream"
#include"cstdio"
using namespace std;
const int maxn=1e5+5;
long long L[maxn],R[maxn],a[maxn];
int main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    int N;
    while(cin>>N&&N)
    {
        a[0]=a[N+1]=-1;
        for(int i=1;i<=N;i++)
        {
            cin>>a[i];
            L[i]=R[i]=i;
        }
        for(int i=1,j=N;i<=N;i++,j--)
        {
            while(a[L[i]-1]>=a[i])L[i]=L[L[i]-1];
            while(a[R[j]+1]>=a[j])R[j]=R[R[j]+1];
        }
        long long Max=0;
        for(int i=1;i<=N;i++)Max=max(Max,a[i]*(R[i]-L[i]+1));
        cout<<Max<<endl;
    }
}

单调栈

单调栈的一个很重要的作用就是能够 O ( n ) 地找出所有点的左边或右边第一个比他 大 或 小 的 数

比如要找右边第一个比他小的数,用单调递增栈,从左往右扫一遍

/*
单调栈
*/
#include"iostream"
#include"stack"
#define top stk.top()
using namespace std;
const int maxn=1e5+5;
long long L[maxn],R[maxn],a[maxn];
int N;
void solveR()//计算右边第一个小于他的数,单调递增栈
{
    stack<int>stk;
    stk.push(0);
    for(int i=1;i<=N+1;i++)
    {

        if(a[i]>a[top]||stk.empty())stk.push(i);
        else
        {
            while(a[i]<a[top])
            {
                R[top]=i;
                stk.pop();
                if(stk.empty())break;
            }
            stk.push(i);
        }
    }
}
void solveL()
{
    stack<int>stk;
    stk.push(N+1);
    for(int i=N;i>=0;i--)
    {

        if(a[i]>a[top]||stk.empty())stk.push(i);
        else
        {
            while(a[i]<a[top])
            {
                L[top]=i;
                stk.pop();
                if(stk.empty())break;
            }
            stk.push(i);
        }
    }
}
int main()
{
    while(cin>>N&&N)
    {
        for(int i=1;i<=N;i++)cin>>a[i];
        a[0]=a[N+1]=-1;
        solveL();
        solveR();
        long long Max=-1;
        for(int i=1;i<=N;i++)
        {
            Max=max(Max,a[i]*(R[i]-L[i]-1));
        }
        cout<<Max<<endl;
    }
}

猜你喜欢

转载自blog.csdn.net/swustlpf/article/details/80961769