线段树模板
2015-07-28 19:26
267 查看
//线段树模板(单点更新) #define Mid ((l+r)>>1) #define lson rt<<1,l,Mid #define rson rt<<1|1,Mid+1,r const int maxn = 100010; int sum[maxn<<2]; void build(int rt,int l,int r) { if(l==r){ scanf("%d",&sum[rt]); }else{ build(lson); build(rson); sum[rt] = sum[rt<<1] + sum[rt<<1|1]; } } void update(int rt,int l,int r,int pos,int num) //修改pos位值为num { if(l == r && r == pos){ sum[rt] += num; }else{ if( pos <= Mid) update(lson,pos,num); else update(rson,pos,num); sum[rt] = sum[rt<<1] + sum[rt<<1|1]; } } int query(int rt,int l,int r,int L,int R) //查询[L,R] { if(L <= l && r <= R){ return sum[rt]; }else{ int tmp = 0; if( L <= Mid) tmp += query(lson,L,R); if( R > Mid) tmp += query(rson,L,R); return tmp; } }
调用例子:
int main() { int n,L,R; while(scanf("%d",&n)!=EOF){ build(1,1,n); scanf("%d%d",&L,&R); update(1,1,n,L,R); scanf("%d%d",&L,&R); printf("%d\n", query(1,1,n,L,R)); //修改L处值为R } return 0; }
//线段树模板(区间更新) #define Mid ((l+r)>>1) #define lson rt<<1,l,Mid #define rson rt<<1|1,Mid+1,r const int maxn = 100010; int sum[maxn<<2],add[maxn<<2]; void build(int rt,int l,int r) { add[rt] = 0; if(l == r){ scanf("%d",&sum[rt]); //省个数组 }else{ build(lson); build(rson); sum[rt]=sum[rt<<1]+sum[rt<<1|1]; } } void pushDown(int rt,int len) { add[rt<<1] = add[rt<<1|1] = add[rt]; sum[rt<<1] = (len-(len>>1))*add[rt]; sum[rt<<1|1] = (len>>1)*add[rt]; add[rt] = 0; } void update(int rt,int l,int r,int L,int R,int z) //更新[L,R]为z { if(L <= l && r <= R){ add[rt] = z; sum[rt] = (r-l+1)*z; }else{ if(add[rt]) pushDown(rt,r-l+1); if(L <= Mid) update(lson,L,R,z); if(R > Mid) update(rson,L,R,z); sum[rt] = sum[rt<<1] + sum[rt<<1|1]; } } int query(int rt,int l,int r,int L,int R) //查询[L,R],调用:(1,1,n,L,R) { if(L <= l && r <= R){ return sum[rt]; }else{ if(add[rt]) pushDown(rt,r-l+1); int t = 0; if(L <= Mid) t += query(lson,L,R); if(R > Mid) t += query(rson,L,R); return t; } }
调用例子:
int main() { int L,R,z; while(scanf("%d%d",&n,&m)!=EOF){ build(1,1,n); while(m--){ scanf("%*c%c",&op); if(op=='C'){ scanf("%d%d%d",&L,&R,&z); update(1,1,n,L,R,z); }else{ scanf("%d%d",&L,&R); printf("%d\n",query(1,1,n,L,R)); } } } }
相关文章推荐
- hdoj3785寻找大富翁(优先队列)
- ZOJ 1004 Anagrams by Stack
- 写自己的第二级处理器(3)——Verilog HDL行为语句
- [hdu5316]线段树
- Javascript对象的创建模式 -- 深入了解Javascript
- hdu5326 树的子树节点个数 dfs
- 输入以逗号分隔的整数,如123,234,345,456,111等,并以回车结束输入
- nyoj757期末考试
- IOS-1-Objective-C-@property属性的使用及注意问题:@property(assign)int name;
- 终于搞定UIScrollView上的几个tableview和collection view之间切换的问题了
- Leetcode# 66 Plus One
- combobox的多选模糊过滤
- HDU 5317 RGCDQ (质数筛法,序列)
- [LintCode] Number of Islands II
- 看图理解单链表的反转
- Ubuntu安装MySQL及MySQL基本使用
- iOS 手势应用
- Setting中格式化SD卡
- hdoj2031进制转换
- iOS中单例的线程安全