单点更新模板(以区间求和为例)

 1 #include<cstdio>
 2 #include<cstring>
 3 #include<algorithm>
 4 using namespace std;
 5 #define lson l,m,rt*2
 6 #define rson m+1,r,rt*2+1 
 7 #define root 1,n,1
 8 const int maxn=100000; //题目所给最大区间
 9 struct node{
10     int sum; //记录附加信息 
11 }arr[maxn*4]; //节点长度开最大区间的四倍
12 
13 void pushup(int rt)
14 {
15     arr[rt].sum=arr[rt*2].sum+arr[rt*2+1].sum;
16 }
17 
18 void build(int l,int r,int rt)
19 {
20     if ( l==r ) {
21         scanf("%d",&arr[rt].sum);
22         return;
23     }
24     int m=(l+r)/2;
25     build(lson);
26     build(rson);
27     pushup(rt);
28 }
29 
30 void update(int p,int add,int l,int r,int rt)
31 {
32     if ( l==r ) {
33         arr[rt].sum+=add;
34         return;
35     }
36     int m=(l+r)/2;
37     if ( p<=m ) update(p,add,lson);
38     else update(p,add,rson);
39     pushup(rt);
40 } 
41 
42 int query(int L,int R,int l,int r,int rt)
43 {
44     if ( L<=l && r<=R ) return arr[rt].sum;
45     int m=(l+r)/2;
46     int ret=0;
47     if ( L<=m ) ret+=query(L,R,lson);  //注意不是左右区间不是if和else的关系,而是并列的关系(拆分区间) 
48     if ( R>m ) ret+=query(L,R,rson);
49     return ret;
50 } 
51 
52 int main()
53 {
54     int n;
55     while ( scanf("%d",&n)!=EOF ) {
56         build(root);
57         //操作 
58     }
59     return 0;
60 }
单点更新

相关文章: