前奏
做树状数组的题之前,需要做三道板子题:
板子题1——单点修改,区间查询
板子题就不写题解了哈╮(╯▽╰)╭
代码
#include<cstdio>
#include<iostream>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<cstdlib>
#define int long long
using namespace std;
int n,q,a[1000005],c[1000005];
void update(int t,int v)
{
for (int x=t; x<=n; x+=x&-x) c[x]+=v;
}
int getsum(int t)
{
int ans=0;
for (int x=t; x; x-=x&-x) ans+=c[x];
return ans;
}
signed main()
{
scanf("%lld%lld",&n,&q);
for (int i=1; i<=n; i++) scanf("%lld",&a[i]),update(i,a[i]);
for (int i=1; i<=q; i++){
int x,l,r;
scanf("%lld%lld%lld",&x,&l,&r);
if (x==1) update(l,r);
if (x==2) printf("%lld\n",getsum(r)-getsum(l-1));
}
return 0;
}
板子题2——区间修改,单点查询
代码
#include<cstdio>
#include<iostream>
#include<iostream>
#include<cmath>
#include<cstring>
#include<algorithm>
#define int long long
using namespace std;
int n,q,a[1000005],c[1000005];
void update(int x,int v)
{
for (; x<=n; x+=x&-x) c[x]+=v;
}
int getsum(int x)
{
int sum=0;
for (; x>0; x-=x&-x) sum+=c[x];
return sum;
}
signed main()
{
scanf("%lld",&n);
scanf("%lld",&q);
int last=0

本文介绍了树状数组的三种基础操作,并提供了详细的代码实现。接着通过四道不同难度的题目,包括数星星、校门外的树、清点人数等,深入讲解了树状数组在实际问题中的应用,适合初学者巩固和提高。

544

被折叠的 条评论
为什么被折叠?



