Color the ball
當N = 0,輸入結束。
已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;
}