线段树,顺序存储实现

#include <stdio.h>
#include <string.h>
const int maxx=32000;
const int maxn=15000;
int l[3*(maxx+1)],h[3*(maxx+1)],w[3*(maxx+1)];
int N;
int ans[maxn];
void Create(int t,int s,int f)
{
	l[t]=s;h[t]=f;
	if(s<f)
	{
		int mid=(s+f)/2;
		Create(2*t+1,s,mid);
		Create(2*t+2,mid+1,f);
	}
}
void Init(int t)
{
	w[t]=0;
	if(l[t]<h[t])
	{
		Init(2*t+1);
		Init(2*t+2);
	}
}
int GetAmount(int t,int f )
{
	if(h[t]==f) return w[t];
	else
	{
		int mid=(l[t]+h[t])/2;
		if(mid>=f) 
			return GetAmount(2*t+1,f);
		else
			return w[2*t+1]+GetAmount(2*t+2,f);
	}
}
void Insert(int t,int x)
{
	if(l[t]<=x&&x<=h[t])
	{
		w[t]++;
		if(l[t]!=h[t])
		{
			int mid=(l[t]+h[t])/2;
			Insert(2*t+1,x);
			Insert(2*t+2,x);
		}
	}
}
int main()
{
	Create(0,0,maxx);
	while(scanf("%d",&N)!=EOF)
	{
		Init(0);
		memset(ans,0,sizeof(ans));
		int i,x,y,level;
		for(i=0;i<N;i++)
		{
			scanf("%d%d",&x,&y);
			level=GetAmount(0,x);
			ans[level]++;
			Insert(0,x);
		}
		for(i=0;i<N;i++)
		{
			printf("%d\n",ans[i]);
		}
	}
	return 0;
}


 

posted on 2012-09-29 14:22  lishimin_come  阅读(96)  评论(0编辑  收藏  举报