HDU 1556 Color the ball(树状数组)

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

树状数组的模板题


AC代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#define maxn 100005
using namespace std;
int pre[maxn];
int n;

int lowbit(int x){return x & (-x);}

void Update(int x,int y){
	for(int i=x;i<=n;i+=lowbit(i)){
		pre[i] += y;
	}
}

int Query(int x){
	int sum = 0;
	for(int i=x;i>=1;i-=lowbit(i)){
		sum += pre[i];
	}
	return sum;
}

int main()
{
	while(~scanf("%d",&n)){
		if(n == 0)break;
		memset(pre,0,sizeof(pre));
		for(int i=0;i<n;i++){
			int x,y;
			scanf("%d%d",&x,&y);
			Update(x,1);
			Update(y+1,-1);
		}
		for(int i=1;i<=n;i++){
			printf("%d%c",Query(i),i==n?'\n':' ');
		}
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/charles_zaqdt/article/details/81142337
今日推荐