一、基本概述
设节点编号为n,则
C[n] = A[n - 2^k + 1] + …… + A[n].
C[n]为所要条件为n时,求和的结果,A[n]是最后一层第n 个叶子节点的值,k是n的二进制时末尾0的个数。
二、2^k的有效率的编程方法
法一:
int lowbit(int x){
return x&-x;
}
法二:
int lowbit(int x){
return x&(x^(x–1));
}
个人比较喜欢法一。
三、有关树状数组的基本操作。
修改操作
void add(int k,int num)
{
while(k<=n)
{
tree[k]+=num;
k+=k&-k;
}
}
查询操作
int read(int k)//1~k的区间和
{
int sum=0;
while(k)
{
sum+=tree[k];
k-=k&-k;
}
return sum;
}
四、经典例题
HDU 1556 Color the ball
Description
N个气球排成一排,从左到右依次编号为1,2,3….N.每次给定2个整数a b(a <= b),lele便为骑上他的“小飞鸽”牌电动车从气球a开始到气球b依次给每个气球涂一次颜色。但是N次以后lele已经忘记了第I个气球已经涂过几次颜色了,你能帮他算出每个气球被涂过几次颜色吗?
Input
每个测试实例第一行为一个整数N,(N <= 100000).接下来的N行,每行包括2个整数a b(1 <= a <= b <= N)。
当N = 0,输入结束。
Output
每个测试实例输出一行,包括N个整数,第I个数代表第I个气球总共被涂色的次数。
Sample Input
3
1 1
2 2
3 3
3
1 1
1 2
1 3
0
Sample Output
1 1 1
3 2 1
树状数组做法:
#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
using namespace std;
const int maxn = 100000 + 5;
int tree[maxn], n;
int sum(int n)
{
int sum1 = 0;
while (n > 0) {
sum1 += tree[n];
n -= n & -n;
}
return sum1;
}
void add(int pos, int num)
{
while (pos <= n) {
tree[pos] += num;
pos += pos & -pos;
}
}
int main()
{
while (cin >> n) {
if (n == 0) break;
int a, b;
memset (tree, 0, sizeof(tree));
for (int i = 0; i < n; i++) {
cin >> a >> b;
add (a, 1);//把a位置所有关联的全都加1
add (b + 1, -1);//把b+1位置所有关联的全都减1
}
for (int i = 1; i < n; i++) {
printf ("%d ", sum (i));
}
printf ("%d\n", sum (n));
}
return 0;
}
网上还有一种特别巧妙的做法,用的是数组:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <map>
#include <algorithm>
#include <iterator>
using namespace std;
const int maxn = 100000 + 5;
int s[maxn], n, j, l;
int main()
{
int n1, sum;
#ifndef ONLINE_JUDGE
freopen("in.txt", "r", stdin);
#endif // ONLINE_JUDGE
while (scanf ("%d", &n) != EOF) {
if (n == 0) break;
n1 = n;
memset (s, 0, sizeof(s));
int a, b;
while (n1--) {
scanf ("%d%d", &a, &b);
s[a]++;//这个是记录有多少的涂色从此开始
s[b + 1]--;//这个是记录有多少的涂色从此结束,结束了就要--
}
sum = s[1];
printf ("%d", s[1]);
for (int i = 2; i <= n; i++) {
sum += s[i];//把所有新开始的都加上(或者把结束的减去)
printf(" %d", sum);
}
printf ("\n");
}
return 0;
}
本文介绍了树状数组的基本概念,包括求和公式、高效计算2^k的方法及树状数组的基本操作。并通过一道经典例题详细展示了树状数组在解决区间更新与查询问题上的应用。
1505

被折叠的 条评论
为什么被折叠?



