树状数组模板2——区间修改,单点查询

树状数组的模板,修改整个区间的值(加上x),查询某个节点,此处展示一个非差分的方法

 1 #include<cstdio>
 2 #include<cctype> 
 3 using namespace std;
 4 
 5 int c[500010],n,m,a[500010];
 6 
 7 int read()
 8 {
 9     int x=0,f=1;
10     char c=getchar();
11     while (!isdigit(c))
12         f=c=='-'?-1:1,c=getchar();
13     while (isdigit(c))
14         x=(x<<1)+(x<<3)+(c^48),c=getchar();
15     return x*f;
16 }
17 
18 int lowbit(int x)
19 {
20     return x&-x;
21 }
22 
23 int query(int x)
24 {
25     int ans=0;
26     for (;x;x-=lowbit(x))
27         ans+=c[x];
28     return ans;
29 }
30 
31 int update(int x,int val)
32 {
33     for (;x<=n;x+=lowbit(x))
34         c[x]+=val;
35 }
36 
37 int main()
38 {
39     int i,j,t,p;
40     n=read(),m=read();
41     for (i=1;i<=n;i++)
42         a[i]=read();
43     while (m--)
44     {
45         t=read();
46         if (t==1)
47         {
48             i=read(),j=read(),p=read();
49             update(i,p);
50             update(j+1,-p);
51         }
52         else
53         {
54             p=read();
55             printf("%d
",a[p]+query(p));
56         }
57     }
58     return 0;
59 }
原文地址:https://www.cnblogs.com/Ronald-MOK1426/p/8848868.html