转载请注明出处:http://blog.csdn.net/u012860063
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1556
3 1 1 2 2 3 3 3 1 1 1 2 1 3 0
1 1 1 3 2 1
解题思路:
树状数组中的每个节点都代表了一段线段区间,每次更新的时候,根据树状数组的特性可以把b以前包含的所有区间都找出来,然后把b之前的区间全部加一次染色次数。然后,再把a之前的区间全部减一次染色次数,这样就修改了树状数组中的[a,b]的区间染色次数,查询每一个点总的染色次数的时候,就可以直接向上统计每个父节点的值,就是包含这个点的所有区间被染色次数,这就是树状数组中向下查询,向上统计的典型应用
树状数组版:
#include <cstdio>
#include <cstring>
#define maxn 100047
int c[maxn];
int n,t;
int Lowbit(int x) // 2^k
{
return x&(-x);
}
void update(int i, int x)//i点增量为x
{
while(i > 0)
{
c[i] += x;
i -= Lowbit(i);
}
}
int sum(int x)//区间求和 [1,x]
{
int sum=0;
while(x <= n)
{
sum+=c[x];
x +=Lowbit(x);
}
return sum;
}
int main()
{
int i,j, x, y;
while(scanf("%d",&n) && n)
{
memset(c,0,sizeof(c));
for(i = 1; i <= n; i++)
{
scanf("%d%d",&x,&y);
update(y,1);//将y以下的区间+1
update(x-1,-1);//将x以下的区间-1
}
for(j = 1; j < n; j++)
{
printf("%d ",sum(j));
}
printf("%d\n",sum(n));
}
return 0;
}
非树状数组版:(其实也是运用了树状数组版的思路)
#include <cstdio>
#include <cstring>
int main()
{
int n, i, j, a[100047], x, y;
while(scanf("%d",&n) && n)
{
memset(a,0,sizeof(a));
for(i = 1; i <= n; i++)
{
scanf("%d%d",&x,&y);
a[x]++,a[y+1]--;
}
int sum = a[1];
printf("%d",a[1]);
for(i = 2; i <= n; i++)
{
sum+=a[i];
printf(" %d",sum);
}
printf("\n");
}
return 0;
}hdu 1556 Color the ball(树状数组),布布扣,bubuko.com
原文:http://blog.csdn.net/u012860063/article/details/35602541