Sum up--RMQ--线段树

来源:互联网 发布:视频图片拼接软件 编辑:程序博客网 时间:2024/05/16 06:55
Description

Given an array a[] with N elements,you areasked to perform several operations,each of them is one of the two kinds:

1.      a[i]=j;

2.      calculate sum(a[x]) wherei<=x<=j;

Input Description
Two integers in the first line:n and m.n(1<=n<=100000) implies the number of the elements,m means the number of operations.And then following m(1<=m<=100000) lines each contain three integers o i j.
Output Description
For each operation with o==2,output sum(a[x]) where i<=x<=j.
Sample Input
3 41 1 11 2 21 3 32 1 3
Sample Output
6
#include <iostream>#include <cstdio>using namespace std;#define maxn 100008struct ST{int l,r,key;}st[4*maxn];int A[maxn];void buildtree(int id,int l,int r){st[id].l=l;st[id].r=r;if(l==r){st[id].key=A[l];return;}int mid=(l+r)/2;buildtree(2*id,l,mid);buildtree(2*id+1,mid+1,r);st[id].key=st[2*id].key+st[2*id+1].key;}void update(int id,int u,int newkey){if(st[id].l==u&&st[id].r==u){st[id].key=newkey;return;}if(st[2*id+1].l<=u){update(2*id+1,u,newkey);st[id].key=st[2*id].key+st[2*id+1].key;return;}if(st[2*id].r>=u){update(2*id,u,newkey);st[id].key=st[2*id].key+st[2*id+1].key;return;}update(2*id+1,u,newkey);update(2*id,u,newkey);st[id].key=st[2*id].key+st[2*id+1].key;}int find(int id,int l,int r){if(st[id].l==l&&st[id].r==r){return st[id].key;}if(st[2*id].r>=r){return find(2*id,l,r);}if(st[2*id+1].l<=l){return find(2*id+1,l,r);}int m1=find(2*id,l,st[2*id].r);int m2=find(2*id+1,st[2*id+1].l,r);return m1+m2;}int main(){int n,m,operate,u,v;scanf("%d%d",&n,&m);buildtree(1,1,n);for(int i=1;i<=m;i++){scanf("%d%d%d",&operate,&u,&v);if(operate==1){update(1,u,v);}else printf("%d\n",find(1,u,v));}return 0;}

原创粉丝点击