【NOI2019模拟】搬砖

Description

小火车很穷,只好去搬砖了。

小火车被工头要求搭建\(n\)座塔,第i个高度为\(H_i\),也就是由\(H_i\)块砖头组成。每次小火车可以携带至多\(k\)块砖头,由某座塔底出发,摆放砖头。他可以向左右两座塔的相同高度摆放砖头(即使是悬空的),也可以向那两个位置移动过去(必须有砖头才能移动),还可以向同一座塔的上一层攀爬(如果那里有砖头的话就直接爬,如果没有的话可以摆上砖头再爬过去),可惜携带砖头的他并不方便向下爬。请问他至少要多少次才能搭建完成呢?

Input

第一行两个整数\(n,k\),表示有\(n\)个纪念塔,每次你可以携带\(k\)块砖头。

第二行有\(n\)个整数表示\(H_i\)。

Output

一行一个整数表示答案。

Sample Input

5 10

2 1 2 1 2

Sample Output

3

不会贪心

因为如果我们从下往上搬砖上去了就下不来了,所以我们考虑倒着做,从上往下搬砖。用到类似的贪心思路的题还有“【NOI2017】蔬菜”。

我们考虑先将区间划分为多个子区间。假设处理区间\([l,r]\),我们设其中的最矮的纪念塔高度为\(H\)。然后我们从高度为\(H\)的位置切一刀。然后可能还剩下一堆小区间,再用同样的方法处理。

比如样例:我们先切一刀,得到了\([1,5](1)\),然后剩下了\([1,1](1),[3,3](1),[5,5](1)\)。我们称\([1,5](1)\)是剩下那些区间的上一级区间。

然后我们考虑从上往下搬砖。假设第\(i\)个区间还需要办\(x\)个砖,那么我们需要搬\(\lceil\frac{x}{k} \rceil\)。然后我们可能剩下了\(k*\lceil\frac{x}{k} \rceil-x\)个砖,那么我们就把它累加到它的上一级区间中。

为什么上面多出来的砖一定可以给上一级的区间贡献呢?因为我们可以理解为我们多出来的砖在经过上一级区间的时候就先摆放了,所以是合法的。

搬砖都搬不来了

代码:

#include<bits/stdc++.h>
#define ll long long
#define N 100005 using namespace std;
inline int Get() {int x=0,f=1;char ch=getchar();while(ch<'0'||ch>'9') {if(ch=='-') f=-1;ch=getchar();}while('0'<=ch&&ch<='9') {x=(x<<1)+(x<<3)+ch-'0';ch=getchar();}return x*f;} int n,k;
int h[N];
struct node {
int l,r;
ll h;
bool operator <(const node &x)const {
if(l!=x.l) return l<x.l;
if(r!=x.r) return r>x.r;
return h<x.h;
}
}t[N];
int L[N],R[N];
int st[N],top;
int fa[N];
vector<int>Line;
bool cmp(const int &a,const int &b) {return t[a].h<t[b].h;}
ll res[N],ans;
int q[N];
int main() {
n=Get(),k=Get();
for(int i=1;i<=n;i++) h[i]=Get();
h[0]=h[n+1]=-1;
st[top=1]=0;
for(int i=1;i<=n;i++) {
while(top&&h[st[top]]>=h[i]) top--;
L[i]=st[top]+1;
st[++top]=i;
}
st[top=1]=n+1;
for(int i=n;i>=1;i--) {
while(top&&h[st[top]]>=h[i]) top--;
R[i]=st[top]-1;
st[++top]=i;
}
for(int i=1;i<=n;i++) t[i]=(node) {L[i],R[i],h[i]};
sort(t+1,t+1+n);
t[0].h=-1;
int tot=0;
for(int i=1;i<=n;i++) {
if(t[tot]<t[i]) t[++tot]=t[i];
}
for(int i=1;i<=tot;i++) {
while(Line.size()&&t[Line.back()].r<t[i].l) Line.pop_back();
if(Line.size()) {
fa[i]=Line.back();
}
Line.push_back(i);
}
for(int i=1;i<=tot;i++) q[i]=i;
sort(q+1,q+1+tot,cmp);
for(int i=tot;i>=1;i--) {
int now=q[i];
if(fa[now]) t[now].h-=t[fa[now]].h;
ll ned=1ll*t[now].h*(t[now].r-t[now].l+1);
if(res[now]>=ned) {
res[now]-=ned;
res[fa[now]]+=res[now];
} else {
ned-=res[now];
ll t=(ned+k-1)/k;
ans+=t;
res[fa[now]]+=t*k-ned;
}
}
cout<<ans;
return 0;
}
04-28 13:14