线段树模板
1 #include<cstdio> 2 #include<cstring> 3 #include<iostream> 4 #include<algorithm> 5 #include<cmath> 6 #include<queue> 7 #define pn putchar(' ') 8 #define pd putchar(' ') 9 #define num ch-'0' 10 #define reint register int 11 using namespace std; 12 template <typename T> 13 void read(T &res) 14 { 15 char ch;bool flag=false; 16 while(!isdigit(ch=getchar()))(ch=='-')&&(flag=true); 17 for(res=num;isdigit(ch=getchar());res=res*10+num); 18 flag&&(res=-res); 19 } 20 template <typename T> 21 void write(T x) 22 { 23 if(x<0)putchar('-'),x=-x; 24 if(x>9)write(x/10); 25 putchar(x%10+'0'); 26 } 27 typedef long long ll; 28 const int INF=0x7fffffff; 29 const int inf=0x3f3f3f3f; 30 const int mod=1000000007; 31 const int maxn=100005; 32 int n,a[maxn],sum[maxn<<2],tag[maxn<<2]; 33 inline int ls(int p) { 34 return p<<1; 35 } 36 inline int rs(int p) { 37 return p<<1|1; 38 } 39 inline void pushup(int p) { 40 sum[p]=sum[ls(p)]+sum[rs(p)]; 41 } 42 inline void f(int p,int l,int r,ll k) { 43 tag[p]+=k; 44 sum[p]+=(r-l+1)*k; 45 } 46 inline void pushdown(int p,int l,int r) { 47 int mid=(l+r)>>1; 48 f(ls(p),l,mid,tag[p]); 49 f(rs(p),mid+1,r,tag[p]); 50 tag[p]=0; 51 } 52 inline void build(int p,int l,int r) { 53 tag[p]=0; 54 if(l==r) { 55 sum[p]=a[l]; 56 return ; 57 } 58 int mid=(l+r)>>1; 59 build(ls(p),l,mid); 60 build(rs(p),mid+1,r); 61 pushup(p); 62 } 63 inline void update(int a,int b,int l,int r,int p,ll k) { 64 if(a<=l&&b>=r) { 65 sum[p]+=(r-l+1)*k; 66 tag[p]+=k; 67 return ; 68 } 69 pushdown(p,l,r); 70 int mid=(l+r)>>1; 71 if(a<=mid) update(a,b,l,mid,ls(p),k); 72 if(b>mid) update(a,b,mid+1,r,rs(p),k); 73 pushup(p); 74 } 75 inline ll query(int a,int b,int l,int r,int p) { 76 ll ans=0; 77 if(a<=l&&b>=r) return sum[p]; 78 pushdown(p,l,r); 79 int mid=(l+r)>>1; 80 if(a<=mid) ans+=query(a,b,l,mid,ls(p)); 81 if(b>mid) ans+=query(a,b,mid+1,r,rs(p)); 82 return ans; 83 } 84 int main() 85 { 86 int m; 87 read(n),read(m); 88 for(int i=1;i<=n;i++) 89 read(a[i]); 90 build(1,1,n); 91 while(m--) { 92 int l,r 93 ll v; 94 char ch; 95 scanf(" %c %d %d",&ch,&l,&r); 96 if(ch=='Q') 97 write(query(l,r,1,n,1)),pn; 98 else if(ch=='C') { 99 scanf("%lld",&v); 100 update(l,r,1,n,1,v); 101 } 102 } 103 return 0; 104 }