码迷,mamicode.com
首页 > 其他好文 > 详细

POJ 3468 A Simple Problem with Integers 线段树 区间更新

时间:2016-02-20 01:48:44      阅读:203      评论:0      收藏:0      [点我收藏+]

标签:

技术分享
  1 #include<iostream>
  2 #include<string>
  3 #include<algorithm>
  4 #include<cstdlib>
  5 #include<cstdio>
  6 #include<set>
  7 #include<map>
  8 #include<vector>
  9 #include<cstring>
 10 #include<stack>
 11 #include<cmath>
 12 #include<queue>
 13 //#include <bits/stdc++.h>
 14 using namespace std;
 15 #define LL long long
 16 const int maxn=100000;
 17 struct node
 18 {
 19     LL sum,val;
 20 }tree[maxn*4];
 21 
 22 void pushup(int rt)
 23 {
 24     tree[rt].sum=tree[rt<<1].sum+tree[rt<<1|1].sum;
 25 }
 26 void pushdown(int rt,int m)
 27 {
 28     if(tree[rt].val)
 29     {
 30         tree[rt<<1].val+=tree[rt].val;
 31         tree[rt<<1|1].val+=tree[rt].val;
 32         tree[rt<<1].sum+=(LL)(m-(m>>1))*tree[rt].val;
 33         tree[rt<<1|1].sum+=(LL)(m>>1)*tree[rt].val;
 34         tree[rt].val=0;
 35     }
 36 }
 37 
 38 void build_tree(int l,int r,int rt)
 39 {
 40     tree[rt].val=0;
 41     if(l==r)
 42     {
 43         scanf("%I64d",&tree[rt].sum);
 44         return ;
 45     }
 46     int m=(l+r)>>1;
 47     build_tree(l,m,rt<<1);
 48     build_tree(m+1,r,rt<<1|1);
 49     pushup(rt);
 50 }
 51 
 52 LL query(int L,int R,int l,int r,int rt)
 53 {
 54     if(L<=l&&r<=R)
 55     {
 56         return tree[rt].sum;
 57     }
 58     int m=(l+r)>>1;
 59     pushdown(rt,r-l+1);
 60     LL ans=0;
 61     if(L<=m)
 62         ans+=query(L,R,l,m,rt<<1);
 63     if(m<R)
 64         ans+=query(L,R,m+1,r,rt<<1|1);
 65     pushup(rt);
 66     return ans;
 67 }
 68 
 69 void update(int L,int R,int add,int l,int r,int rt)
 70 {
 71     if(L<=l&&r<=R)
 72     {
 73         tree[rt].sum+=(LL)add*(r-l+1);
 74         tree[rt].val+=add;
 75         return;
 76     }
 77     pushdown(rt,r-l+1);
 78     int m=(l+r)>>1;
 79     if(L<=m)
 80         update(L,R,add,l,m,rt<<1);
 81     if(R>m)
 82         update(L,R,add,m+1,r,rt<<1|1);
 83     pushup(rt);
 84 }
 85 
 86 int main()
 87 {
 88     int n,a,b,q;
 89     LL c;
 90     while(~scanf("%d%d",&n,&q))
 91     {
 92         build_tree(1,n,1);
 93         char s[3];
 94         while(q--)
 95         {
 96             scanf("%s",s);
 97             if(s[0]==Q)
 98             {
 99                 cin>>a>>b;
100                 cout<<query(a,b,1,n,1)<<endl;
101             }
102             else if(s[0]==C)
103             {
104                 cin>>a>>b>>c;
105                 update(a,b,c,1,n,1);
106             }
107         }
108     }
109     return 0;
110 }
View Code

 

POJ 3468 A Simple Problem with Integers 线段树 区间更新

标签:

原文地址:http://www.cnblogs.com/ITUPC/p/5202534.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!