您的位置:首页 > 其它

线段树入门 单点更新区间查询 南阳oj 116

2017-09-12 10:15 423 查看


线段树入门基础题,直接模板单点更新区间查询,下面贴AC代码:

#include<stdio.h>
int a[3000000];
void build(int l,int r,int node)
{
if(l==r)
{
scanf("%d",&a[node]);
return;
}
int m=(l+r)/2;
build(l,m,node*2);
build(m+1,r,node*2+1);
a[node]=a[node*2]+a[node*2+1];
}
int query(int ql,int qr,int l,int r,int node)
{
if(l>=ql&&r<=qr)
return a[node];
int m,ans=0;
m=(l+r)/2;
if(m<ql)
ans+=query(ql,qr,m+1,r,node*2+1);
else if(m>=qr)
ans+=query(ql,qr,l,m,node*2);
else
{
ans+=query(ql,qr,m+1,r,node*2+1);
ans+=query(ql,qr,l,m,node*2);
}
return ans;
}
void update(int l,int r,int k,int add,int node)
{
a[node]+=add;
if(l==r)
return;
int m=(l+r)/2;
if(m<k)
update(m+1,r,k,add,node*2+1);
else
update(l,m,k,add,node*2);
}
int main()
{
int n,m,i;
scanf("%d%d",&n,&m);
build(1,n,1);
while(m--)
{
int l,r,k,add;
char s[10];
scanf("%s",s);
if(s[0]=='Q')
{
scanf("%d%d",&l,&r);
printf("%d\n",query(l,r,1,n,1));
}
else
{
scanf("%d%d",&k,&add);
update(1,n,k,add,1);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: