❤️[29st]❤️P5609 ❤️[Ynoi2013] ❤️对数据结构的爱❤️

· · 题解

29st Ynoi,切题地,情人节快乐。

小清新数据结构题,好久之前的了。补题解。

比较像线段树维护分段函数。但你不能直接维护 f_{[l,r]}(x) 代表初值 x 代入区间 [l,r] 执行运算后的答案,这样函数的端点太多了,达到了 2^n。

我们发现这个运算后的答案,就是区间的总和减去一些 p。这是个很好的性质。考虑维护 f_{[l,r]}(x) 表示 x 作初值代入区间 [l,r] 运算后,减去了几个 p。注意到 f_{[l,r]}(x)\in[0,r-l+1],并且明显 x 越大减去 p 个数只会变多,即函数单调不降,且端点数规模只有区间长度,可以维护。

维护起来比较好看的。线段树上每个区间对于 0\le i\le 区间长度,维护能减去 i 个 p 的最小初值 c_i(最大的是 c_{i+1}-1)。

现在考虑怎么把左右子树的信息 push_up,我们枚举 x,对于左子树的初值 [c_{x},c_{x+1}) 而言,它们代入左子树的运算会减去 x 个 p,那么整个区间运算的结果就是另一个区间 [c_x+s_{lc}-x\times p,c_{x+1}+s_{lc}-x\times p),其中 s_{lc} 是左子树区间和。

我们把这个新区间代入右子树的 c^\prime,它又会被分成若干区间,一一带入算即可。

但这样复杂度不太对。可以证明 c_x-x\times p 的单调性,即左子树终值的单调性。有点感性,大概就是对于 c_x 而言它在经历运算的时候需要必有一个减到 0 的过程,否则就可以被继续调小。于是我们至少要增大 p 才能再减一个 p,即 c_{x+1}-c_x\ge p。

至此可以双指针枚举左边区间带入到右边的位置,预处理复杂度 O(n\log n),询问考虑一一将前面答案代入后面计算,计算就在 c 数组上二分,总复杂度 O(n\log n+q\log^2 n)。

#include<bits/stdc++.h>
using namespace std;

using ll = long long;

const int N = 1e6 + 5;

int n,m,a[N];
ll p,s[N << 2];
vector<ll> c[N << 2];

#define lc (i << 1)
#define rc (lc | 1)
#define mid ((L + R) >> 1)

void psu(int i,int L,int R){
    s[i] = s[lc] + s[rc];
    for(int x = 0,y = 0;x <= mid - L + 1;++x)
        for(y = min(y,R - mid);y <= R - mid;++y){
            if(c[rc][y] > c[lc][x + 1] - 1 - p * x + s[lc]){ --y; break; }
            c[i][x + y] = min(c[i][x + y],max(c[lc][x],c[rc][y] + p * x - s[lc]));
        }
}

void build(int i,int L,int R){
    c[i].assign(R - L + 3,ll(1e18)),c[i][0] = -1e18;
    if(L == R) return void(c[i][1] = p - (s[i] = a[L]));
    build(lc,L,mid); build(rc,mid + 1,R); psu(i,L,R);
}

ll qry(int l,int r,int i,int L,int R,ll v){
    if(l == L && R == r)
        return v + s[i] - p * (upper_bound(begin(c[i]),end(c[i]),v) - begin(c[i]) - 1);
    if(r <= mid) return qry(l,r,lc,L,mid,v);
    if(l > mid) return qry(l,r,rc,mid + 1,R,v);
    return qry(mid + 1,r,rc,mid + 1,R,qry(l,mid,lc,L,mid,v));
}

int main(){
    scanf("%d%d%lld",&n,&m,&p);
    for(int i = 1;i <= n;++i) scanf("%d",a + i);
    build(1,1,n);
    for(int l,r;m--;){
        scanf("%d%d",&l,&r);
        printf("%lld\n",qry(l,r,1,1,n,0));
    }
    return 0;
}