您的位置:首页 > 其它

hdu 1556 Color the ball(线段树)

2013-05-04 15:15 363 查看
我的第一道线段树!

说出这句话的时候一阵心酸,之前一直说要学,看看又觉得好难啊,往后推。一直推到今天,咬咬牙,终于学了。虽然只是很简单的做了一道题,甚至线段树的思想还掌握不了,可毕竟是一个开端啊。

#include<stdio.h>
#define N 1000005
struct node
{
int x,y;
int count;
}a[N*2];
void CreatTree(int t,int x,int y)
{
int temp=t*2;
int mid=(x+y)/2;
if(x==y)
return ;
a[t].x=x;
a[t].y=y;
a[t].count=0;
if(x+1==y)
return ;
CreatTree(temp,x,mid);
CreatTree(temp+1,mid,y);
return ;
}
void InsertTree(int t,int x,int y)
{
int mid=(a[t].x+a[t].y)/2;
int temp=t*2;
if(a[t].x==x&&a[t].y==y)
a[t].count++;
else if(y<=mid)
InsertTree(temp,x,y);
else if(x>=mid)
InsertTree(temp+1,x,y);
else
{
InsertTree(temp,x,mid);
InsertTree(temp+1,mid,y);
}
return ;
}
int CountTree(int t,int x,int y)
{
int mid=(a[t].x+a[t].y)/2;
int temp=t*2;
if(x==a[t].x&&y==a[t].y)
return a[t].count;
int sum=0;
if(x>=a[t].x&&y<=a[t].y)
{
sum+=a[t].count;
if(y<=mid)
sum+=CountTree(temp,x,y);
else if(x>=mid)
sum+=CountTree(temp+1,x,y);
}
return sum;
}
int main()
{
int n,x,y,i;
while(scanf("%d",&n),n)
{
CreatTree(1,1,n+1);
for(i=0;i<n;i++)
{
scanf("%d%d",&x,&y);
InsertTree(1,x,y+1);
}
printf("%d",CountTree(1,1,2));
for(i=2;i<=n;i++)
printf(" %d",CountTree(1,i,i+1));
printf("\n");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: