设 表示前 个人最后一个人受到了 的伤害。
这样可以做到 。
我们发现有很多状态是没用的,考虑如何去掉一维。我们考虑什么 是有用的。
- 直接继承。 不变。
- 为了要选 ,把 变大为
- 为了不要 ,把 变小为
所以我们只需要更新 和 两种情况,其它直接保留就行。于是不看第一维,线段树维护 和 的 就可以转移了。每次只需要单点修改,区间加上 就行。
我们注意到,只有 这两个个值是有用的,离散化就可以做到只有 个位置。所以最终的时间复杂度是 。
#include<bits/stdc++.h>
#ifndef __linux__
#define gc getchar
#define pc putchar
#else
#define gc getchar_unlocked
#define pc putchar_unlocked
#endif
#define ll long long
#define pii pair<int,int>
#define fi first
#define se second
#define rep(i,a,b) for(int i=a;i<=b;++i)
#define per(i,a,b) for(int i=a;i>=b;--i)
#define debug(x) cerr<<#x<<'='<<x<<'\n'
using namespace std;
namespace IO{
template<typename T>
inline void read(T &x){
x=0;bool f=1;
char c=gc();
while(c<'0'||c>'9'){if(c=='-')f=0;c=gc();}
while(c>='0'&&c<='9') x=(x<<1)+(x<<3)+(c^48),c=gc();
x=f?x:-x;
}
template<typename T>
void write(T x){
if(x<0) pc('-'),x=-x;
if(x>9) write(x/10);
pc(x%10+'0');
}
inline void read(char &x){while(isspace(x=gc()));}
inline void read(string &x){
x.clear();
char c=gc();
while(isspace(c)&&c!=EOF) c=gc();
while(!isspace(c)&&c!=EOF) x.push_back(c),c=gc();
}
inline void write(char x){pc(x);}
inline void write(string x){for(auto c:x) pc(c);}
};using namespace IO;
const int N=5e5+5;
const ll inf=9e18;
int n,m,tot;
ll a[N],b[N<<1],c[N];
inline ll v(ll x){return lower_bound(b+1,b+tot+1,x)-b;}
struct SGT{
#define ls i<<1
#define rs i<<1|1
ll t[N<<3],tag[N<<3];
inline void pushup(int i){
t[i]=max(t[ls],t[rs]);
}
inline void addtag(int i,ll x){
t[i]+=x,tag[i]+=x;
}
inline void pushdown(int i){
if(tag[i]){
addtag(ls,tag[i]);
addtag(rs,tag[i]);
tag[i]=0;
}
}
void build(int i,int l,int r){
t[i]=-inf,tag[i]=0;
if(l==r) return;
int mid=(l+r)>>1;
build(ls,l,mid);
build(rs,mid+1,r);
}
void upd(int i,int il,int ir,int x,ll k){
if(il==ir){t[i]=max(t[i],k);return;}
pushdown(i);
int mid=(il+ir)>>1;
if(x<=mid) upd(ls,il,mid,x,k);
else upd(rs,mid+1,ir,x,k);
pushup(i);
}
void add(int i,int il,int ir,int l,int r,ll x){
if(l<=il&&ir<=r){addtag(i,x);return;}
pushdown(i);
int mid=(il+ir)>>1;
if(l<=mid) add(ls,il,mid,l,r,x);
if(r>mid) add(rs,mid+1,ir,l,r,x);
pushup(i);
}
ll ask(int i,int il,int ir,int l,int r){
if(l<=il&&ir<=r) return t[i];
pushdown(i);
int mid=(il+ir)>>1;ll mx=-inf;
if(l<=mid) mx=ask(ls,il,mid,l,r);
if(r>mid) mx=max(mx,ask(rs,mid+1,ir,l,r));
return mx;
}
}t1,t2;
inline void solve(){
read(n),read(m);tot=0;
rep(i,1,n) read(a[i]),read(c[i]);
rep(i,1,n) b[++tot]=a[i],b[++tot]=a[i]-1;
sort(b+1,b+tot+1);
tot=unique(b+1,b+tot+1)-b-1;
t1.build(1,0,tot),t2.build(1,0,tot);
t1.upd(1,0,tot,0,0),t2.upd(1,0,tot,0,0);
rep(i,1,n){
int p=v(a[i]);
ll dp1=t1.ask(1,0,tot,0,p-1)-a[i]*m,dp2=t2.ask(1,0,tot,p,tot);
// cerr<<dp1<<' '<<dp2<<'\n';
// cerr<<dp2+(a[i]-1)*m<<' '<<dp2<<' '<<dp1+a[i]*m<<' '<<dp1<<'\n';
t1.upd(1,0,tot,p-1,dp2+(a[i]-1)*m),t2.upd(1,0,tot,p-1,dp2);
t1.upd(1,0,tot,p,dp1+a[i]*m),t2.upd(1,0,tot,p,dp1);
t1.add(1,0,tot,p,tot,c[i]),t2.add(1,0,tot,p,tot,c[i]);
}
write(t2.t[1]),pc('\n');
}
signed main(){
int T;read(T);
while(T--) solve();
return 0;
}