1313C2 - Skyscrapers (hard version)(思维+单调栈+前缀和)

40 篇文章 0 订阅
5 篇文章 0 订阅

https://codeforces.com/problemset/problem/1313/C2


思路:

可以发现答案是某点做最高峰的开口向下的二次函数。

对于一个点,如果其左边存在能比他大的数,那么就可以拉平,如果比其下,那么就要更新最大值。于是对于每一个数,我们要快速找到其最近的比他小的数。也就是维护某个数作为最大值的区间范围。那么就是单调栈。

维护好之后就可以跑前缀和

左边的贡献值:左边第一个小于等于他的点的pre[l[i]]+m[i]*这两点之间的距离。

右边的贡献值:右边第一个小于等于他的点的suf[r[i]]+m[i]*这两点的距离。

然后枚举。取出最值。得出方案。

#include<iostream>
#include<vector>
#include<queue>
#include<cstring>
#include<cmath>
#include<stack>
#include<map>
#include<set>
#include<cstdio>
#include<algorithm>
#define debug(a) cout<<#a<<"="<<a<<endl;
using namespace std;
const int maxn=5e5+1000;
typedef long long LL;
inline LL read(){LL x=0,f=1;char ch=getchar();	while (!isdigit(ch)){if (ch=='-') f=-1;ch=getchar();}while (isdigit(ch)){x=x*10+ch-48;ch=getchar();}
return x*f;}
LL a[maxn];
LL l[maxn],r[maxn];
LL pre[maxn],suf[maxn];
int main(void){
   cin.tie(0);std::ios::sync_with_stdio(false);
   LL n;cin>>n;
   for(LL i=1;i<=n;i++){
      cin>>a[i];
   }
   stack<LL>s;
   a[0]=a[n+1]=0;
   for(LL i=1;i<=n;i++){
      while(!s.empty()&&a[s.top()]>=a[i]) s.pop();
      if(!s.empty()) l[i]=s.top();
      else l[i]=0;
      s.push(i);
   }
   while(!s.empty()) s.pop();
   for(LL i=n;i>=1;i--){
      while(!s.empty()&&a[s.top()]>=a[i]) s.pop();
      if(!s.empty()) r[i]=s.top();
      else r[i]=n+1;
      s.push(i);
   }
   for(LL i=1;i<=n;i++){
       pre[i]=pre[l[i]]+(i-l[i])*a[i];
   }
   for(LL i=n;i>=1;i--){
       suf[i]=suf[r[i]]+(r[i]-i)*a[i];
   }
   LL ans=0;LL pos=0;
   for(LL i=1;i<=n;i++){
      if(pre[i]+suf[i]-a[i]>ans){
         ans=pre[i]+suf[i]-a[i];
         pos=i;
      }
   }
   vector<LL>v1,v2;
   LL h1=a[pos];
   v1.push_back(h1);
   for(LL i=pos-1;i>=1;i--){
      if(a[i]>=h1){
        v1.push_back(h1);
      }
      else if(a[i]<h1){
        h1=a[i];
        v1.push_back(h1);
      }
   }
   reverse(v1.begin(),v1.end());
   h1=a[pos];
   for(LL i=pos+1;i<=n;i++){
      if(a[i]>=h1){
        v2.push_back(h1);
      }
      else if(a[i]<h1){
        h1=a[i];
        v2.push_back(h1);
      }
   }
   for(auto i:v1){
     cout<<i<<" ";
   }
   for(auto i:v2){
     cout<<i<<" ";
   }cout<<"\n";
   return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值