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

树状数组区间修改与查询
本文介绍了一种使用树状数组进行区间修改(加上指定值x)和节点查询的有效方法。通过示例代码展示了如何实现这些操作,包括读取输入、更新区间以及查询特定位置的值。

树状数组的模板,修改整个区间的值(加上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\n",a[p]+query(p));
56         }
57     }
58     return 0;
59 }

 

转载于:https://www.cnblogs.com/Ronald-MOK1426/p/8848868.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值