自己写的一个关于线段树的代码

#include <iostream> using namespace std; #define max(a,b) a>b?a:b struct LineTree { int left,right; int cover; LineTree *lchild,*rchild; }; LineTree* CreateTree(int a,int b) //建立线段树 { LineTree *root; root=new LineTree; root->left=a; root->right=b; root->cover=0; if(b-a>1) { int mid; mid=(a+b)/2; root->lchild=CreateTree(a,mid); root->rchild=CreateTree(mid,b); } return root; } void Insert(LineTree *t,int a,int b) //插入 { int mid; if(t->left>=a && t->right<=b) t->cover++; else { mid=(t->left+t->right)/2; if(b<=mid) Insert(t->lchild,a,b); else if(mid<=a) Insert(t->rchild,a,b); else { Insert(t->lchild,a,mid); Insert(t->rchild,mid,b); } } } void Del(LineTree *t,int a,int b) //删除 { int mid; if(t->left>=a && t->right<=b) t->cover--; else { mid=(t->left+t->right)/2; if(b<=mid) Del(t->lchild,a,b); else if(mid<=a) Del(t->rchild,a,b); else { Del(t->lchild,a,mid); Del(t->rchild,mid,b); } } } int sum; void point_count(LineTree *t,int a) //计算a点的个数 { if(t->left<=a && t->right>=a) sum+=t->cover; if(t->right-t->left>1) { point_count(t->lchild,a); point_count(t->rchild,a); } } int main() { int x,y; LineTree *s; cin>>x>>y; s=CreateTree(x,y); cin>>x>>y; Insert(s,x,y); cin>>x>>y; Insert(s,x,y); cin>>x>>y; Insert(s,x,y); int p1,p2,p3; cin>>p1>>p2>>p3; sum=0; point_count(s,p1); printf("%d/n",sum); sum=0; point_count(s,p2); printf("%d/n",sum); sum=0; point_count(s,p3); printf("%d/n",sum); return 0; }

你可能感兴趣的:(自己写的一个关于线段树的代码)