树状数组的区间修改、区间查询

设原数组第 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[i1]

那么 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=1xj=1id[j]=i=1x(xi+1)d[i]=(x+1)i=1xd[i]i=1xid[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=1xid[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 ;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值