郁郁青青 长过千寻

树状数组

    树形结构

  1. 一维
    1. component
      1. LOWBIT(x)
      2. UPDATE(i,v)
      3. SUM(i)
    2. 单点更新 区间查询
    3. 区间更新 单点查询
    4. 区间更新 区间查询
      1. UPDATE(i,v)
      2. SUM(i)
  2. 二维
    1. component
      1. UPDATE(x,y,v)
      2. SUM(x,y)
    2. 单点更新 区间查询
    3. 区间更新 单点查询
    4. 区间更新 区间查询
      1. UPDATE(x,y,v)
      2. SUM(x,y)

一维

component

LOWBIT(x)

1
return x&(-x)

UPDATE(i,v)

1
2
3
4
while i<n
btree[i]=btree[i]+v
i=i+lowbit(i)
endwhile

SUM(i)

1
2
3
4
5
6
res=0
while i>0
res=res+btree[i]
i=i-lowbit(i)
endwhile
return res

单点更新 区间查询

1
2
3
for i=1 to n
update(i,v) endfor
res=sum(r)-sum(l-1)

区间更新 单点查询

1
2
3
update(l,v)
update(r+1,-v)
res=sum(i)

区间更新 区间查询

UPDATE(i,v)

1
2
3
4
5
6
p=i
while i<n
sum1[i]=sum1+v
sum2[i]=sum2+p*v
i=i+lowbit(i)
endwhile

SUM(i)

1
2
3
4
5
6
7
res=0
p=i
while i>0
res=res+(p+1)*sum1[i]-sum2[i]
i=i=lowbit(i)
endwhile
return res
1
2
3
update(l,v)
update(r+1,-v)
res=sum(r)-sum(l-1)

二维

component

UPDATE(x,y,v)

1
2
3
for i=x to n step lowbit(i)
for j=y to n step lowbit(j)
btree[i][j]=btree[i][j]+v

SUM(x,y)

1
2
3
4
5
res=0
for i=x to 1 step lowbit(i)
for j=y to 1 step lowbit(j)
res=res+btree[i][j]
return res

单点更新 区间查询

1
2
3
x=x-1
y=y-1
return sum(xx,yy)+sum(x,y)-query(xx,y)-query(x,yy)

区间更新 单点查询

1
2
3
4
5
update(x,y,v)
update(x,yy+1,-v)
update(xx+1,y,-v)
update(xx+1,yy+1,v)
sum(a,b)

区间更新 区间查询

UPDATE(x,y,v)

1
2
3
4
5
6
for i=x to n step lowbit(i)
for j=y to n step lowbit(j)
btree1[i][j]=v
btree2[i][j]=v*x
btree3[i][j]=v*y
btree4[i][j]=v*x*y

SUM(x,y)

1
2
3
4
5
res=0
for i=x to 1 step lowibt(i)
for j=y to 1 step lowbit(j)
res=res+(x+1)*(y+1)*btree1[i][j]-(y+1)*btree2[i][j]-(x+1)*btree3[i][j]+btree4[i][j]
return res
1
2
3
4
5
update(x,y,v)
update(x,yy+1,-v)
update(xx+1,y,-v)
update(xx+1,yy+1,v)
return sum(aa,bb)+sum(a-1,b-1)-sum(a-1,bb)-sum(aa,b-1)
页阅读量:  ・  站访问量:  ・  站访客数: