upd on 1.9:修改一些 typo,并添加了代码。
比天天爱打卡难很多吧???关键的性质想不出来就会不了。
A 性质是简单的,但不太具有扩展性。观察一下,我们并不关心具体操作了哪些区间,不妨考虑一个士兵被操作了几次,令 代表前 个士兵,第 个士兵操作了 次的最大收益。枚举上一个士兵操作了 次,有转移:
最后一项代表当 时,有 次操作可以从操作 的那些区间中继承过来,剩下 次操作需要新开。直接前后缀 优化转移可以做到 。
似乎有一个优化方向是直接上整体 dp 做到 ,但想了想发现其实不太能做,有两个维度,每次对于每个 都要求前后缀 。
看起来没有前途了,大失败。这个时候不妨先从如何通过减少第二维的状态量入手,先考虑如何做到 。有一个关键的性质:称 为最终位置 操作了几次,则必然存在一组最优解满足 。即一个位置要么操作 次,要么操作 次,要么完全从前面继承过来。正确性是比较好理解的,因为当 时我们不会希望这个士兵死掉。
那么将 离散化后作为 的第二维就可以做到 了。而且我们会发现这个性质对进一步的优化是很有前途的!本质上我们要将 划分成若干连续段,每一段的开头是 。考虑整体 dp,分不开新段和开新段两种情况:不开新段直接有 ;开新段的 只有 两种取值,因此我们只需做两次查询和单点改即可!
此时有 ,将 两种情况拆开,分别维护 的后缀 和 的前缀 ,查区间 就行了。只需写一棵区间加、区间 的线段树,复杂度 。
#include<bits/stdc++.h>
using namespace std;
const int N=1e6+5;
long long n,n_,m;
long long a[N],b[N],c[N];
struct tree{
int l,r;
long long tag,f,g;
}t[N*4];
void pushup(int u){
t[u].f=max(t[u*2].f,t[u*2+1].f),t[u].g=max(t[u*2].g,t[u*2+1].g);
}
void build(int u,int l,int r){
t[u].l=l,t[u].r=r,t[u].tag=0;
if(l==r){
t[u].f=(l==0?0:-1e18),t[u].g=t[u].f+c[l]*m;
return;
}
int mid=l+(r-l)/2;
build(u*2,l,mid),build(u*2+1,mid+1,r),pushup(u);
}
void pushdown(int u){
t[u*2].f+=t[u].tag,t[u*2].g+=t[u].tag,t[u*2].tag+=t[u].tag;
t[u*2+1].f+=t[u].tag,t[u*2+1].g+=t[u].tag,t[u*2+1].tag+=t[u].tag;
t[u].tag=0;
}
void update(int u,int l,int r,long long x){
if(l<=t[u].l&&t[u].r<=r){
t[u].f+=x,t[u].g+=x,t[u].tag+=x;
return;
}
if(!(l>t[u].r||r<t[u].l)) pushdown(u),update(u*2,l,r,x),update(u*2+1,l,r,x),pushup(u);
}
void update_(int u,int x,long long y){
if(t[u].l==t[u].r){
if(y>t[u].f) t[u].f=y,t[u].g=t[u].f+c[t[u].l]*m;
return;
}
pushdown(u);
if(x<=t[u*2].r) update_(u*2,x,y);
else update_(u*2+1,x,y);
pushup(u);
}
long long query(int u,int l,int r,int type){
if(l<=t[u].l&&t[u].r<=r) return (type==1?t[u].f:t[u].g);
if(!(l>t[u].r||r<t[u].l)){
pushdown(u);
return max(query(u*2,l,r,type),query(u*2+1,l,r,type));
}
return -1e18;
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
int T;
cin>>T;
while(T--){
cin>>n>>m;
for(int i=1;i<=n;i++) cin>>a[i]>>b[i];
n_=0;
for(int i=1;i<=n;i++) c[++n_]=a[i],c[++n_]=a[i]-1;
sort(c+1,c+n_+1);
n_=unique(c+1,c+n_+1)-c-1;
build(1,0,n_);
for(int i=1;i<=n;i++){
int pos=lower_bound(c+1,c+n_+1,a[i])-c,pos1=lower_bound(c+1,c+n_+1,a[i]-1)-c;
update_(1,pos,max(query(1,pos,n_,1),query(1,0,pos,2)-c[pos]*m));
update_(1,pos1,max(query(1,pos1,n_,1),query(1,0,pos1,2)-c[pos1]*m));
update(1,pos,n_,b[i]);
}
cout<<t[1].f<<'\n';
}
return 0;
}