[省选前题目整理][POJ 3468]A Simple Problem with Integers(线段树区间修改)
2015-04-11 15:40
218 查看
题目链接
http://poj.org/problem?id=3468题目大意
要求对一个序列支持查询区间和、对给定区间中所有元素加同一值。思路
经典的线段树区间修改、区间求和模板题。代码
#include <iostream> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <algorithm> #define MAXN 401000 using namespace std; typedef long long int LL; LL a[MAXN]; LL sum[MAXN],addtag[MAXN]; void pushup(int o) { sum[o]=sum[o<<1]+sum[o<<1|1]; } void pushdown(int o,int L,int R) { if(addtag[o]) { int M=(L+R)>>1; addtag[o<<1]+=addtag[o]; addtag[o<<1|1]+=addtag[o]; sum[o<<1]+=(M-L+1)*addtag[o]; sum[o<<1|1]+=(R-M)*addtag[o]; addtag[o]=0; } } void build(int o,int L,int R) { if(L==R) { sum[o]=a[L]; addtag[o]=0; return; } LL M=(L+R)>>1; build(o<<1,L,M); build(o<<1|1,M+1,R); pushup(o); addtag[o]=0; } void update(int o,int L,int R,int ql,int qr,LL addv) { if(ql<=L&&R<=qr) { addtag[o]+=addv; sum[o]+=(R-L+1)*addv; //!!!!! return; } pushdown(o,L,R); int M=(L+R)>>1; if(ql<=M) update(o<<1,L,M,ql,qr,addv); if(qr>M) update(o<<1|1,M+1,R,ql,qr,addv); pushup(o); } LL query(int o,int L,int R,int ql,int qr) { if(ql<=L&&R<=qr) return sum[o]; pushdown(o,L,R); int M=(L+R)>>1; LL ans=0; if(ql<=M) ans+=query(o<<1,L,M,ql,qr); if(qr>M) ans+=query(o<<1|1,M+1,R,ql,qr); return ans; } int main() { int n,q; scanf("%d%d",&n,&q); for(int i=1;i<=n;i++) scanf("%lld",&a[i]); build(1,1,n); for(int i=1;i<=q;i++) { char cmd[4]; LL ql,qr,val; scanf("%s%lld%lld",cmd,&ql,&qr); if(cmd[0]=='C') { scanf("%lld",&val); update(1,1,n,ql,qr,val); } else printf("%lld\n",query(1,1,n,ql,qr)); } return 0; }
相关文章推荐
- POJ 3468 A Simple Problem with Integers 线段树区间修改
- poj 3468 A Simple Problem with Integers【线段树区间修改】
- poj 3468 : A Simple Problem with Integers 【线段树 区间修改】
- POJ_3468 A Simple Problem with Integers(线段树区间修改+附线段树模板)
- POJ - 3468 - A Simple Problem with Integers 【线段树 区间修改】
- POJ 3468 A Simple Problem with Integers 线段树 区间修改
- POJ-3468-A Simple Problem with Integers(线段树区间修改+区间求和)
- POJ 3468 A Simple Problem with Integers (线段树区间修改查询)
- POJ 3468 A Simple Problem with Integers (线段树区间修改)
- poj 3468:A Simple Problem with Integers(线段树,区间修改求和)
- 模板(线段树 + 树状数组 + 区间修改 + 区间查询)eg:POJ 3468 - A Simple Problem with Integers
- POJ 3468 A Simple Problem with Integers(线段树区间修改)
- poj 3468 A Simple Problem with Integers(线段树区间修改+区间求和)
- POJ-3468-A Simple Problem with Integers(线段树区间修改)
- POJ 3468 :A Simple Problem with Integers——区间更新线段树经典题目
- POJ 3468 A Simple Problem with Integers(线段树区间修改)
- POJ 3468 A Simple Problem with Integers 线段树区间修改
- POJ 题目3468 A Simple Problem with Integers(线段树成段更新,区间求和)
- 20140719 「线段树 - 区间更新,区间求和」 POJ 3468 A Simple Problem with Integers
- Poj 3468 A Simple Problem with Integers (线段树 区间更新 区间求和)