http://codevs.cn/problem/1080/
分析:
单值修改、区间求和 入门题目
AC代码:
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <vector>
#include <stack>
#include <queue>
#include <map>
#include <set>
#include<list>
#include <bitset>
#include <climits>
#include <algorithm>
#define gcd(a,b) __gcd(a,b)
#define FIN freopen("input.txt","r",stdin)
#define FOUT freopen("output.txt","w",stdout)
typedef long long LL;
const LL mod=1e9+7;
const int INF=0x3f3f3f3f;
const int MAX=1e6+5;
const double PI=acos(-1.0);
using namespace std;
LL a[MAX];
struct Tree{
int l,r;
LL val;
}T[MAX];
void build(int rt,int l,int r){// 建树
T[rt].l=l;
T[rt].r=r;
if (l==r) {
T[rt].val=a[l];
return ;
}
int mid=(l+r)/2;
build(rt*2,l,mid);
build(rt*2+1,mid+1,r);
T[rt].val=T[rt*2].val+T[rt*2+1].val;
}
void update(int rt,int index,int e){// 单值修改
if (T[rt].l==T[rt].r){
if (T[rt].l==index)
T[rt].val+=e;
return ;
}
int mid=(T[rt].l+T[rt].r)/2;
if (index<=mid) update(rt*2,index,e);
else update(rt*2+1,index,e);
T[rt].val=T[rt*2].val+T[rt*2+1].val;
}
LL Query (int rt,int Ql,int Qr){// 查询
if (T[rt].l>=Ql&&T[rt].r<=Qr) return T[rt].val;
int mid=(T[rt].l+T[rt].r)/2;
LL ans=0;
if (Ql<=mid) ans+=Query(rt*2,Ql,Qr);
if (Qr>mid) ans+=Query(rt*2+1,Ql,Qr);
return ans;
}
int main (){
int n;
while(scanf ("%d",&n)!=EOF){
for (int i=1;i<=n;i++) scanf ("%lld",&a[i]);
build(1,1,n);
int m;
scanf ("%d",&m);
while (m--){
int x;
scanf ("%d",&x);
if (x==1){
int s,v;
scanf ("%d%d",&s,&v);
update(1,s,v);
}
else{
int s,e;
scanf ("%d%d",&s,&e);
printf ("%lld\n",Query(1,s,e));
}
}
}
return 0;
}
本文介绍了一种基于线段树的数据结构实现,用于解决单值修改与区间求和问题。通过实例演示了如何构建线段树、更新节点值及查询指定区间的和。适用于初学者了解线段树的基本原理及其应用。
927

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



