简介
树状数组是一种真正的“高级”数据结构,它用到了二分思想、二叉树、位运算、前缀和等多种知识,是颇为复杂的数据结构。不过树状数组的编程却不麻烦,其代码简短,效率也高。
解决动态区间和问题
public class Main {
/*
求动态区间和
*/
public static void main(String[] args) {
int []a={0,4,5,6,7,8,9,10,11,12,13}; //注意:a[0]不用
int n=a.length;
int []tree=new int[n];
for (int i = 1; i < n; i++) {
update(i,a[i],tree,n);
}
System.out.println(sum(8,tree)-sum(4,tree));//计算5-8的区间和
}
public static void update(int x,int d,int []tree,int n) {
//修改元素 a[x],a[x] = a[x] + d
while (x<=n){
tree[x]=tree[x]+d;
x=x+Integer.lowestOneBit(x);
}
}
public static int sum(int x,int []tree){
//返回前缀和 sum = a[1] + a[2] +...+ a[x]
int ans=0;
while (x>0){
ans=ans+tree[x];
x=x-Integer.lowestOneBit(x);
}
return ans;
}
}