樹狀陣列的區間修改
參考部落格: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);
}