题解 CF1313C2 【Skyscrapers (hard version)】

· · 题解

有C1和C2。

唯一的差别是 n 的取值。

观察性质可以发现要满足条件必定有一个最高点,使得从左边到最高点高度单调不递减,从右边到最高点高度单调不递减。

C1的做法可以是枚举最高点,计算最优答案。

做法是 O(n^2) 的。

考虑优化找最高点这一个过程。

用数组 l_i,r_i 表示以 i 为最高点时,向左和向右的高度和。

那么求出对于每一个 l_i,r_i 总高度就是 (l_i+r_i-a_i),求 max (l_i+r_i-a_i) 就可以计算答案了。

而求出 l_i,r_i 过程用单调栈实现可以做到 O(n)。

循环一次 1->n , 比 a_i 小的最右的点记做 j,那么 l_i = l_j + a_i*(i-j)。

同理可倒序求 r_i。

部分代码:

    for(ri i=1;i<=n;++i)
    {
        while(top&&a[s[top]]>a[i]) top--;
        int now=s[top];
        l[i]=l[now]+a[i]*(i-now);
        s[++top]=i;
    }
    while(top) top--;
    s[++top]=n+1;
    for(ri i=n;i>=1;--i)
    {
        while(top&&a[s[top]]>a[i]) top--;
        int now=s[top];
        r[i]=r[now]+a[i]*(now-i);
        s[++top]=i;
    }

求出了峰值所在,就可以愉快地求出答案数组了。

别忘了开 long long!

code:

#include“bits/stdc++.h”
using namespace std;
#define ll long long
#define ul unsigned long long
#define ui unsigned int
define ri register int
inline ll read(){
    ll x=0,flag=1;
    char ch=getchar();
    while(ch<'0'||ch>'9'){if(ch=='-') flag=-1;ch=getchar();}
    while(ch>='0'&&ch<='9'){x=x*10+(ch^48);ch=getchar();}
    return x*flag;
}
ll a[500010],l[500010],r[500010],s[500010],top;
int main()
{
    int n=read();
    for(ri i=1;i<=n;++i)
    a[i]=read();
    for(ri i=1;i<=n;++i)
    {
        while(top&&a[s[top]]>a[i]) top--;
        int now=s[top];
        l[i]=l[now]+a[i]*(i-now);
        s[++top]=i;
    }
    while(top) top--;
    s[++top]=n+1;
    for(ri i=n;i>=1;--i)
    {
        while(top&&a[s[top]]>a[i]) top--;
        int now=s[top];
        r[i]=r[now]+a[i]*(now-i);
        s[++top]=i;
    }
    ll maxn=0,pos=0;
    for(ri i=1;i<=n;++i)
    {
        if(l[i]+r[i]-a[i]>maxn)
        {
            pos=i;
            maxn=l[i]+r[i]-a[i];
        }
    }
    int pre=a[pos];
    for(ri i=pos;i;--i)
    {
        if(a[i]>pre) a[i]=pre;
        pre=a[i];
    }
    pre=a[pos];
    for(ri i=pos;i<=n;++i)
    {
        if(a[i]>pre) a[i]=pre;
        pre=a[i];
    }
    for(ri i=1;i<=n;++i)
    printf("%lld ",a[i]);
    return0;
}