当要频繁的对数组元素进行修改,同时又要频繁的查询数组内任一区间元素之和的时候,可以考虑使用树状数组. |
|
update(int i,int x){
while(i<=n){
c[i]=c[i]+x;
i=i+lowbit(i);
}
}
如:Sun(1)=C[1]=A[1];
Sun(2)=C[2]=A[1]+A[2];
Sun(3)=C[3]+C[2]=A[1]+A[2]+A[3];
Sun(4)=C[4]=A[1]+A[2]+A[3]+A[4];
Sun(5)=C[5]+C[4];
Sun(6)=C[6]+C[4];
Sun(7)=C[7]+C[6]+C[4];
Sun(8)=C[8];
,,,,,,
int Sum(int n) //求前n项的和.
{
int sum=0;
while(n>0)
{
sum+=C[n];
n=n-lowbit(n);
}
return sum;
}
lowbit(1)=1 lowbit(2)=2 lowbit(3)=1 lowbit(4)=4
lowbit(5)=1 lowbit(6)=2 lowbit(7)=1 lowbit(8)=8
lowbit(9)=1 lowbit(10)=2 lowbit(11)=1 lowbit(12)=4
lowbit(13)=1 lowbit(14)=2 lowbit(15)=1 lowbit(16)=16
lowbit(17)=1 lowbit(18)=2 lowbit(19)=1 lowbit(20)=4
lowbit(21)=1 lowbit(22)=2 lowbit(23)=1 lowbit(24)=8
lowbit(25)=1 lowbit(26)=2 lowbit(27)=1 lowbit(28)=4
lowbit(29)=1 lowbit(30)=2 lowbit(31)=1 lowbit(32)=32
lowbit(33)=1 lowbit(34)=2 lowbit(35)=1 lowbit(36)=4
lowbit(37)=1 lowbit(38)=2 lowbit(39)=1 lowbit(40)=8
lowbit(41)=1 lowbit(42)=2 lowbit(43)=1 lowbit(44)=4
lowbit(45)=1 lowbit(46)=2 lowbit(47)=1 lowbit(48)=16
lowbit(49)=1 lowbit(50)=2 lowbit(51)=1 lowbit(52)=4
lowbit(53)=1 lowbit(54)=2 lowbit(55)=1 lowbit(56)=8
lowbit(57)=1 lowbit(58)=2 lowbit(59)=1 lowbit(60)=4
lowbit(61)=1 lowbit(62)=2 lowbit(63)=1 lowbit(64)=64
private void Modify(int i, int j, int delta){
A[i][j]+=delta;
for(int x = i; x< A.length; x += lowbit(x))
for(int y = j; y
(2)在二维情况下,求子矩阵元素之和∑ a[i][j](前i行和前j列)的函数为
int Sum(int i, int j){
int result = 0;
for(int x = i; x > 0; x -= lowbit(x)) {
for(int y = j; y > 0; y -= lowbit(y)) {
result += C[x][y];
}
}
return result;
}
比如:
Sun(1,1)=C[1][1]; Sun(1,2)=C[1][2]; Sun(1,3)=C[1][3]+C[1][2];...
Sun(2,1)=C[2][1]; Sun(2,2)=C[2][2]; Sun(2,3)=C[2][3]+C[2][2];...
Sun(3,1)=C[3][1]+C[2][1]; Sun(3,2)=C[3][2]+C[2][2];
你可能感兴趣的:(算法,二维树状数组)