您的位置:首页 > 其它

CODE[VS] 1080 线段树练习(单值修改、区间求和)

2017-09-26 15:20 477 查看
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息