参考博客:https://blog.csdn.net/fsahfgsadhsakndas/article/details/52650026
树状数组的最基本的操作单点修改,以及区间求和
单点修改:
void add(int pos,int num)
{
while(pos < MAXN)
{
tree[pos] += num;
pos += pos & -pos;
}
return ;
}
区间求和:
int read(int pos)
{
int sum = 0;
while(pos > 0)
{
sum += tree[pos];
pos -= pos & -pos;
}
return sum;
}
然后重点就在我们的区间更新以及固定区间查询的问题上了。
我们假设函数sigma(a,i)表示的是求解a数组前i项的和,原数组:a[n],查分数组:c[n]、
其中差分数组的定义:c[n] = a[n] - a[n-1]
知道了差分数组的定义,那么我们就可以得到命题:a[i] = sigma(c,i);
证明:c[1] + c[2] + c[3] + c[4] +...+ c[n] = a[1] - a[0] + a[2] - a[1] + ... +a[n] - a[n-1] = a[n] - a[0];
这里a数组的0位置是不储存任何元素的,那么上面的命题就的得证。
那么我们要修改区间[l,r]的数值的话,我们只需要对差分数组c进行修改即可:c[i] += v,c[j+1] -= v;
然后我们现在说明区间求和:
a[1] + a[2] + a[3] +... + a[n]
= c[1] + (c[1] + c[2]) + (c[1] + c[2] + c[3]) + ... + (c[1] + c[2] +c[3] +... +c[n])
= n*c[1] + (n-1)*c[2] + ... + c[n]
= n(c[1] + c[2] + ... + c[n]) - (0*c[1] + 1 * c[2] + ... + (n-1) * c[n])
我们令数组 c2[i] = (i-1) * c[i];
这样我们的求和就可已使用上面的函数sigma来求解了: = n*sigma(c,n) -sigma(c2,n)
这样区间更新就结束了,下面就是代码的实现过程了:
sigma函数:
int sigma(int a[],ll pos)
{
ll ans = 0;
while(pos)
{
ans += a[pos];
pos -= pos&-pos;
}
return ans;
}
add函数:
void add(ll a[],int pos, int num)
{
while(pos < MAXN)
{
a[pos] += num;
pos += pos&-pos;
}
return ;
}
然后在我们更新的时候会有一些区别
区间更新:在[l,r]之间加v
add(c1,l,v);
add(c1,r+1,-v);
add(c2,l,v*(l-1));
add(c2,r+1,-v*r);
区间求和:[l,r]区间
int sum1 = (l-1)*sigma(c1,l-1) - sigma(c2,l-1);
int sum2 = r *sigma(c1,r) - sigma(c2,r);
int ans = sum2 - sum1;
整体的程序:
#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <queue>
#include <vector>
#include <set>
#define ll long long
using namespace std;
const int MAXN = 100100;
ll c1[MAXN],c2[MAXN],num[MAXN];
int n;
ll lowbit(ll x)
{
return x & -x;
}
ll sigma(ll *a,ll pos)
{
ll ans = 0;
while(pos)
{
ans += a[pos];
pos -= lowbit(pos);
}
return ans;
}
void add(ll a[],int pos, ll num)
{
while(pos < MAXN)
{
a[pos] += num;
pos += lowbit(pos);
}
return ;
}
int main()
{
scanf("%d",&n);
for(int i = 1;i <= n;i++)
{
scanf("%I64d",num+i);
add(c1,i,num[i] - num[i-1]);
add(c2,i,(i-1)*(num[i]-num[i-1]));
}
//首先进行区间的更新操作
ll l,r,v;
scanf("%I64d%I64d%I64d",&l,&r,&v);
add(c1,l,v);add(c1,r+1,-v);
add(c2,l,v*(l-1));add(c2,r+1,-v*r);
//然后进行区间求和操作
scanf("%I64d%I64d",&l,&r);
ll sum1 = (l-1)*sigma(c1,l-1) - sigma(c2,l-1);
ll sum2 = r *sigma(c1,r) - sigma(c2,r);
printf("%I64d\n",sum2 - sum1);
}