您的位置:首页 > 其它

ACM 线段树模板(模板)

2014-10-01 10:28 197 查看
#include <iostream>

using namespace std;

struct Node
{
int Sum;
int Delay;
Node *pLeft,*pRight;
};

void Init(Node **pNode,int Left,int Right)
{
Node *pNew=new Node;

if(Right-Left==1)
{
pNew->Delay=pNew->Sum=0;
pNew->pLeft=pNew->pRight=NULL;
}
else
{
int mid=(Right+Left)>>1;
pNew->Sum=0;
pNew->Delay=0;
Init(&pNew->pLeft,Left,mid);
Init(&pNew->pRight,mid,Right);
}
*pNode=pNew;
}

void Add(Node *pNode,int ID,int val,int Left,int Right)
{
if(Right-Left==1)
{
pNode->Sum+=val;
}
else
{
int mid=(Left+Right)>>1;

if(ID<mid)
{
Add(pNode->pLeft,ID,val,Left,mid);
}
else
{
Add(pNode->pRight,ID,val,mid,Right);
}
pNode->Sum=pNode->pLeft->Sum+pNode->pRight->Sum;
}
}

void Add(Node *pNode,int a,int b,int val,int Left,int Right)
{
if(a<=Left && Right>=b)
{
pNode->Sum+=val*(Right-Left);
pNode->Delay+=val;
}
else
{
int mid=(Right+Left)>>1;
if(pNode->Delay)
{
pNode->pLeft->Sum+=pNode->Delay*(mid-Left);
pNode->pLeft->Delay+=pNode->Delay;
pNode->pRight->Sum+=pNode->Delay*(Right-mid);
pNode->pRight->Delay+=pNode->Delay;
pNode->Delay=0;
}

if(a<mid)
Add(pNode->pLeft,a,b,val,Left,mid);
if(b>mid)
Add(pNode->pRight,a,b,val,mid,Right);
pNode->Sum=pNode->pLeft->Sum+pNode->pRight->Sum;
}
}

int Sum(Node *pNode,int a,int b,int Left,int Right)
{
if(a<=Left && Right<=b)
{
return pNode->Sum;
}
else
{
cout<<Left<<","<<Right<<endl;
int s1=0,s2=0;
int mid=(Left+Right)>>1;

if(a<mid)
s1=Sum(pNode->pLeft,a,b,Left,mid);
if(b>mid)
s2=Sum(pNode->pRight,a,b,mid,Right);

return s1+s2;
}
}

int Sum2(Node *pNode,int a,int b,int Left,int Right)
{
if(a<=Left && Right<=b)
{
cout<<Left<<","<<Right<<endl;
return pNode->Sum;
}
else
{
int s1=0,s2=0;
int mid=(Left+Right)>>1;
if(pNode->Delay)
{
pNode->pLeft->Sum+=pNode->Delay*(mid-Left);
pNode->pLeft->Delay+=pNode->Delay;
pNode->pRight->Sum+=pNode->Delay*(Right-mid);
pNode->pRight->Delay+=pNode->Delay;
pNode->Delay=0;
}

if(a<mid)
s1=Sum2(pNode->pLeft,a,b,Left,mid);
if(b>mid)
s2=Sum2(pNode->pRight,a,b,mid,Right);

return s1+s2;
}
}

int main()
{
int n;

Node *pNode;
Init(&pNode,0,5);
Add(pNode,0,1,0,5);
Add(pNode,1,2,0,5);
Add(pNode,2,3,0,5);
Add(pNode,3,4,0,5);
Add(pNode,4,5,0,5);
Add(pNode,0,3,5,0,5);
cout<<Sum2(pNode,0,3,0,5);

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: