码迷,mamicode.com
首页 > 编程语言 > 详细

hdu 1556 Color the ball(树状数组)

时间:2015-01-08 12:45:23      阅读:169      评论:0      收藏:0      [点我收藏+]

标签:

转载请注明出处:http://blog.csdn.net/u012860063

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1556


Problem 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

解题思路:

树状数组中的每一个节点都代表了一段线段区间,每次更新的时候,依据树状数组的特性能够把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, a, b; 
    while(scanf("%d",&n) && n) 
    { 
        memset(c,0,sizeof(c)); 
        for(i = 1; i <= n; i++)
        { 
            scanf("%d%d",&a,&b);
            update(b,1);//将y下面的区间+1
			update(a-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(树状数组)

标签:

原文地址:http://www.cnblogs.com/gcczhongduan/p/4210306.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!