HDOJ 1556 Color the ball(樹狀數組 & 線段樹)

Color the ball

Time Limit: 9000/3000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 13560    Accepted Submission(s): 6809


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
 

Author
8600
題目鏈接:HDOJ 1556 Color the ball(樹狀數組 & 線段樹)

已AC代碼一:(樹狀數組)

#include<cstdio>
#include<cstring>
#define M 100010
int n,tree[M];
int lowbit(int i)
{
	return i & (-i);
}
void updata(int pos,int val)
{
	while(pos>0)//更新 1~pos的值 
	{
		tree[pos]+=val;
		pos-=lowbit(pos);
	}
}
int Query(int pos)
{
	int sum=0;
	while(pos<=n)
	{
		sum+=tree[pos];
		pos+=lowbit(pos);
	}
	return sum;
}

int main()
{
	int i,a,b;
	while(scanf("%d",&n),n)
	{
		memset(tree,0,sizeof(tree));
		for(i=1;i<=n;++i)
		{
			scanf("%d%d",&a,&b);
			updata(b,1);//從 1 到 b 加一 
			updata(a-1,-1);//從1 到 a-1 減一 
		}
		printf("%d",Query(1));
		for(i=2;i<=n;++i)
		{
			printf(" %d",Query(i));
		}
		printf("\n");
	}
	return 0;
}
已AC代碼二:(線段樹)
#include<cstdio>
#include<cstring>
#define M 100010

struct TREE{
	int left,right,sum;
}tree[M*4];
int n,sum,num[M];

void build(int l,int r,int root)//建樹 
{
	tree[root].left=l;
	tree[root].right=r;
	tree[root].sum=0;//初始爲 0 
	if(l==r)
		return ;
	int mid=(tree[root].left+tree[root].right)>>1;
	build(l,mid,root<<1);
	build(mid+1,r,root<<1|1);
}
void updata(int l,int r,int root)//更新 
{
	if(tree[root].left==l && tree[root].right==r)
	{
		tree[root].sum++;//區間都加一 
		return ;
	}
	if(tree[root].left==tree[root].right)//單點返回 
		return ;
	int mid=(tree[root].left+tree[root].right)>>1;
	if(r<=mid)
		updata(l,r,root<<1);
	else if(l>mid)
		updata(l,r,root<<1|1);
	else
	{
		updata(l,mid,root<<1);//注意 
		updata(mid+1,r,root<<1|1);
	}
}
void Query(int pos,int root)//查詢 
{
	sum+=tree[root].sum;
	if(tree[root].left==tree[root].right)
		return ;
	int mid=(tree[root].left+tree[root].right)>>1;
	if(pos<=mid)
		Query(pos,root<<1);
	else
		Query(pos,root<<1|1);
}
int main()
{
	int i,a,b;
	while(scanf("%d",&n),n)
	{
		build(1,n,1);
		for(i=1;i<=n;++i)
		{
			scanf("%d%d",&a,&b);
			updata(a,b,1);//從 a 到 b 加一 
		}
		for(i=1;i<=n;++i)
		{
			if(i!=1)
				printf(" ");
			sum=0;
			Query(i,1);
			printf("%d",sum);
		}
		printf("\n");
	}
	return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章