当前位置:   article > 正文

[笛卡尔树 树形DP] ICPC 2016 Hong Kong G. Scaffolding_【icpc 2016 hong kong g】脚手架scaffolding

【icpc 2016 hong kong g】脚手架scaffolding

你要搭一个一共n列的脚手架,第i列放Hi根竹子。
你每次只能搬m根竹子上脚手架,并且只能在脚手架左右和向上移动。同时如果左边右边和上面没有竹子,也可以放一根竹子在那里。
问最少需要多少次搬完。
n100000

直接建笛卡尔树 考虑从高往底拆 然后就可以树形DP了
fi表示拆子树i到他的father的高度需要的次数
gi可以顺带算出表示拆了后还剩几根多出来可以拆

#include<cstdio>
#include<cstdlib>
#include<algorithm>
using namespace std;
typedef long long ll;

inline char nc(){
  static char buf[100000],*p1=buf,*p2=buf;
  return p1==p2&&(p2=(p1=buf)+fread(buf,1,100000,stdin),p1==p2)?EOF:*p1++;
}
inline void read(int &x){
  char c=nc(),b=1;
  for (;!(c>='0' && c<='9');c=nc()) if (c=='-') b=-1;
  for (x=0;c>='0' && c<='9';x=x*10+c-'0',c=nc()); x*=b;
}

const int N=100005;

int n,m,a[N];
int sta[N],p;

int rt,ls[N],rs[N],size[N]; ll sum[N];
ll f[N],g[N];

inline void dp(int x,int fa){
  if (!x) return;
  dp(ls[x],x); dp(rs[x],x);
  sum[x]=sum[ls[x]]+sum[rs[x]]+a[x];
  size[x]=size[ls[x]]+size[rs[x]]+1;
  f[x]=f[ls[x]]+f[rs[x]];
  ll rest=(ll)(a[x]-a[fa])*size[x];
  rest-=g[ls[x]]+g[rs[x]];
  if (rest>0) f[x]+=(rest+m-1)/m;
  g[x]=(ll)f[x]*m-(sum[x]-(ll)a[fa]*size[x]);
}

int main(){
  freopen("t.in","r",stdin);
  freopen("t.out","w",stdout);
  read(n); read(m);
  for (int i=1;i<=n;i++) read(a[i]);
  p=0;
  for (int i=1;i<=n;i++){
    int last=0;
    while (p && a[sta[p]]>=a[i]) last=sta[p],sta[p--]=0;
    if (p) rs[sta[p]]=i; else rt=i;
    ls[i]=last,sta[++p]=i;
  }
  dp(rt,0);
  printf("%lld\n",f[rt]);
  return 0;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/weixin_40725706/article/detail/793382
推荐阅读
相关标签
  

闽ICP备14008679号