题目传送门
区间操作可以多想想分治
若当前分治到的区间为 [ L , R ] [L,R] [L,R] ,那么我们考虑 横跨 m i d mid mid 的区间的合法个数. 接下来提到的左端点 l l l 和右端点 r r r 均满足 l ≤ m i d , r ≥ m i d + 1 l\le mid , r\ge mid+1 l≤mid,r≥mid+1
按 m i d → L mid \to L mid→L 的顺序枚举 l l l ,计算 合法的 r r r 的数量
设 S u m = ∑ i = l m i d b i , M I N = min i = l m i d { a i } Sum=\sum_{i=l}^{mid} b_i ,MIN=\min_{i=l}^{mid}\{a_i\} Sum=∑i=lmidbi,MIN=mini=lmid{ai}
设 s s i = ∑ j = m i d + 1 i b j , M I i = min j = m i d + 1 i { a j } ss_i=\sum_{j=mid+1}^{i}b_j , MI_i=\min_{j=mid+1}^{i}\{a_j\} ssi=∑j=mid+1ibj,MIi=minj=mid+1i{aj}
若 p p p 为最大的满足 m i n m i d + 1 p { a i } > M I N min_{mid+1}^{p}\{a_i\} > MIN minmid+1p{ai}>MIN
那么对于 [ m i d + 1 , p ] [mid+1,p] [mid+1,p] 的位置 p o s pos pos , 需要满足 S u m + M I N + s s p o s ≤ S Sum + MIN + ss_{pos} \le S Sum+MIN+sspos≤S ,即 s s p o s ≤ S − ( S u m + M I N ) ss_{pos} \le S-(Sum + MIN) sspos≤S−(Sum+MIN)
对于 [ p + 1 , R ] [p+1,R] [p+1,R] 的位置 p o s pos pos ,需要满足 S u m + M I p o s + s s p o s ≤ S Sum + MI_{pos} + ss_{pos} \le S Sum+MIpos+sspos≤S ,即 M I p o s + s s p o s ≤ S − S u m MI_{pos}+ss_{pos} \le S-Sum MIpos+sspos≤S−Sum
用平衡树之类的数据结构维护一下就好了
#include
#include
#define rep(i,j,k) for(int i=j;i<=k;i++)
#define _rep(i,j,k) for(int i=k;i>=j;i--)
using ll = long long ;
using namespace std;
const int N=2e5+7;
int n;
ll S;
ll a[N],b[N];
struct Balanced_Tree {
int root=0,tot=0,rk[N],sz[N],ls[N],rs[N];
ll val[N];
void Push_up(int rt) {
sz[rt]=sz[ls[rt]]+sz[rs[rt]]+1;
}
int Merge(int x,int y) {
if(!x||!y) return x|y;
if(rk[x]=r) return (a[l]+b[l]<=S)?1ll:0ll;
int mid=(l+r)>>1; ll res=0;
vector MI(r-mid+5,1e18),ss(r-mid+5);
for(int i=mid+1,j=1;i<=r;i++,j++) {
MI[j]=min(MI[j-1],a[i]) , ss[j]=ss[j-1]+b[i];
BT.Insert(ss[j]+MI[j]);
}
int p1=mid; ll sum=0,MIN=1e18;
_rep(i,l,mid) {
sum+=b[i],MIN=min(MIN,a[i]);
while(p1MIN) {
p1++;
BT.Erase(ss[p1-mid]+MI[p1-mid]);
_BT.Insert(ss[p1-mid]);
}
res+=BT.Query(S-sum) + _BT.Query(S-sum-MIN);
}
BT.Clear(),_BT.Clear();
return res+solve(l,mid)+solve(mid+1,r);
}
int main() {
// freopen("tx.in","r",stdin);
// freopen("tx.out","w",stdout);
scanf("%d%lld",&n,&S);
rep(i,1,n) scanf("%lld",&a[i]);
rep(i,1,n) scanf("%lld",&b[i]);
printf("%lld\n",solve(1,n));
return 0;
}
对于不开 l o n g l o n g long\quad long longlong ,是原罪.