题解 CF1313C2 【Skyscrapers (hard version)】
有C1和C2。
唯一的差别是
观察性质可以发现要满足条件必定有一个最高点,使得从左边到最高点高度单调不递减,从右边到最高点高度单调不递减。
C1的做法可以是枚举最高点,计算最优答案。
做法是
考虑优化找最高点这一个过程。
用数组
那么求出对于每一个
而求出
循环一次
同理可倒序求
部分代码:
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;
}