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; }
相关文章推荐
- [ACM_数据结构] 线段树模板
- ACM_模板_线段树
- ACM模板——区间问题(线段树 RMQ-ST)模板
- ACM 线段树模板 hdu 4893 Wow! Such Sequence!
- ACM_线段树模板(区间更新)
- ACM模板——各种各样的线段树
- ACM常用模板——数据结构——线段树
- ACM_线段树模板(单点更新)
- 线段树模板(区间和+区间最大值 + LAZY标记)
- [ACM] hdu 1754 I Hate It (线段树,单点更新)
- 线段树模板整理
- ACM_模板_Tarjan算法
- 线段树区间更新模板
- 线段树模板(求最大最小)
- 【ACM - 搜索模板】
- 线段树专题—POJ 3667 Hotel(区间合并模板)
- ACM学习历程——HDU2227 Find the nondecreasing subsequences(线段树 && dp)
- 啊好久没写了- -。。。 现在又开始系统的刷题了,所以还是写写吧- - 首先附上第一道线段树模板题- -。。。
- ACM 乘法逆元 模板
- “玲珑杯”ACM比赛 Round #18 C -- 图论你先敲完模板【Dp】