当要频繁的对数组元素进行修改,同时又要频繁的查询数组内任一区间元素之和的时候,可以考虑使用树状数组. |
|
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
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];
import java.util.Arrays;
public class Test{
int[][] A;//原二维数组
int[][] C;//对应的二维树状数组
public Test(){
A=new int[5][6];
C=new int[5][6];
for(int i=1;i<5;i++)
for(int j=1;j<6;j++)
Modify(i,j,1);//给A[][]每个元素加1
for(int i=1;i<5;i++){
for(int j=1;j<6;j++)
System.out.print(A[i][j]+" ");//输出A[][]
System.out.println();
}
System.out.println(Sum(3,4));//求子二维数组的和
Modify(2,3,4);//将A[2][3]加4
System.out.println(Sum(3,4));//显示修改后的和
}
private int lowbit(int t){
return t&(-t);
}
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;
}
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 java Test
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
12
16