推荐几篇好的线段树解析以及模板题
https://www.cnblogs.com/xenny/p/9801703.html
https://www.luogu.com.cn/problem/P3372
C++ 代码
#include <bits/stdc++.h>
using namespace std;
const int maxn=100010;
int a[210000],n,m,k,x,y;
struct node
{
int l;
int r;
int sum;
//int lazy;
} tree[4*maxn+2];
//void push_down(int u)
//{
// if(tree[u].sum)
// {
// tree[u*2].sum+=tree[u].lazy*(tree[u*2].r-tree[u*2].l+1);
// tree[u*2+1].sum+=tree[u].lazy*(tree[u*2+1].r-tree[u*2+1].l+1);
// tree[u*2].lazy+=tree[u].lazy;
// tree[u*2+1].lazy+=tree[u].lazy;
// tree[u].lazy=0;
// }
//}
void buildtree(int u,int left,int right)
{
tree[u].l=left;
tree[u].r=right;
if(left==right)
{
tree[u].sum=a[left];
return;
}
int mid=(left+right)>>1;
buildtree(u<<1,left,mid);
buildtree(u<<1|1, mid+1,right);
tree[u].sum=tree[u<<1].sum+tree[u<<1|1].sum;
}
void change(int u,int left,int right,int x,int y)
{
if(left==right)
{
a[x]+=y;
tree[u].sum+=y;
return;
}
int mid=(left+right)>>1;
if(x<=mid)
{
change(u<<1,left,mid,x,y);
}
else
{
change(u<<1|1,mid+1,right,x,y);
}
tree[u].sum=tree[u<<1].sum+tree[u<<1|1].sum;
}
int check(int u,int x,int y)
{
if(x<=tree[u].l&&y>=tree[u].r)
{
return tree[u].sum;
}
//push_down(u);
int mid=(tree[u].l+tree[u].r)>>1;
int t=0;
if(x<=mid)
{
t+=check(u<<1,x,y);
}
if(y>mid)
{
t+=check(u<<1|1,x,y);
}
return t;
}
int main()
{
ios::sync_with_stdio(false);
cin>>m>>n;
for(int i=1; i<=m; i++)
{
cin>>a[i];
}
buildtree(1,1,m);
for(int i=1; i<=n; i++)
{
cin>>k>>x>>y;
if(k==0)
{
int temp=check(1,x,y);
cout<<temp<<endl;
}
if(k==1)
{
change(1,1,m,x,y);
}
}
return 0;
}
蒟蒻题解刚会打模板QWQ