刚学树状数组,样例过不了,求助!

P3374 【模板】树状数组 1

```cpp for(int i=1;i<=n;i++) { cin>>a; tree[i]=i; } ``` ![](https://cdn.luogu.com.cn/upload/image_hosting/ya1v8uql.png)
by xfrvq @ 2021-10-02 20:16:29


[~~oi-wike~~](https://oi-wiki.org/ds/fenwick/)
by VanishmentThisWorld @ 2021-10-02 20:17:11


```cpp #include<iostream> #include<cstdio> #include<cstring> #include<algorithm> #include<cmath> #include<queue> #include<vector> #include<map> #define mem(a,b) memset(a,b,sizeof(a)) #define INF 0x3fffffff #define ll long long using namespace std; inline int read() { char ch=getchar();int x=0,cf=1; while(ch<'0'||ch>'9'){if(ch=='-')cf=-1;ch=getchar();} while(ch>='0'&&ch<='9'){x=(x<<3)+(x<<1)+(ch^48);ch=getchar();} return x*cf; } int n,m,xx,yy,z,a; int tree[505550]; int lowbit(int x) { return x&(-x); } int find(int x) { int ans=0; for(;x>0;x-=lowbit(x)) { ans+=tree[x]; } return ans; }//单点查询 int secfind(int x,int y) { return find(y)-find(x-1); }//区间查询 void update(int x,int k) { for(;x<=n;x+=lowbit(x)) { tree[x]+=k; } }//单点修改 int main() { cin>>n>>m; for(int i=1;i<=n;i++) { cin>>a;update(i,a); } for(int i=1;i<=m;i++) { cin>>z>>xx>>yy; if(z==1) { update(xx,yy); } if(z==2) { cout<<secfind(xx,yy)<<endl; } } return 0; } ```
by VanishmentThisWorld @ 2021-10-02 20:19:31


@[宋子岩yyds](/user/485244) 为什么这么赋值啊?
by Sin_qwq @ 2021-10-02 20:22:33


@[Sin_qwq](/user/324573) 考虑到将i这个位置更改为a时,同时会对他的上级产生影响,所以要update。
by VanishmentThisWorld @ 2021-10-02 20:26:14


@[宋子岩yyds](/user/485244) 谢谢大佬,我悟了。
by Sin_qwq @ 2021-10-02 20:29:17


|