设原数组第 i i i位为 a [ i ] a[i] a[i], a [ 0 ] = 0 a[0]=0 a[0]=0, d [ i ] = a [ i ] − a [ i − 1 ] d[i]=a[i]-a[i-1] d[i]=a[i]−a[i−1]
那么 a [ x ] = ∑ i = 1 x d [ i ] a[x]=\sum _{i=1} ^{x} d[i] a[x]=∑i=1xd[i]
∑ i = 1 x a [ i ] = ∑ i = 1 x ∑ j = 1 i d [ j ] = ∑ i = 1 x ( x − i + 1 ) d [ i ] = ( x + 1 ) ∑ i = 1 x d [ i ] − ∑ i = 1 x i ∗ d [ i ] \sum _{i=1} ^{x} a[i] = \sum _{i=1} ^{x} \sum _{j=1} ^{i} d[j] = \sum _{i=1} ^{x} (x-i+1)d[i] = (x+1) \sum _{i=1} ^{x}d[i] - \sum _{i=1} ^{x} i * d[i] ∑i=1xa[i]=∑i=1x∑j=1id[j]=∑i=1x(x−i+1)d[i]=(x+1)∑i=1xd[i]−∑i=1xi∗d[i]
即原数组差分后,维护 ∑ i = 1 x d [ i ] \sum _{i=1} ^{x}d[i] ∑i=1xd[i]和 ∑ i = 1 x i ∗ d [ i ] \sum _{i=1} ^{x} i * d[i] ∑i=1xi∗d[i]即可
inline int lowbit (int x) {return x & (-x);}
inline void update (int pos, ll val) {
for (int i = pos; i <= n; i += lowbit (i)) {
c1[i] += val; c2[i] += 1ll * pos * val ;
}
}
inline ll cal (int pos) {
ll res = 0 ;
for (int i = pos; i; i -= lowbit (i))
res += c1[i] * (pos + 1) - c2[i] ;
return res ;
}