#include<bits/stdc++.h>
using namespace std;
const int N=1e5+10;
int arr[N],tree[2*N]={0};
void build_tree(int arr[],int tree[], int node, int start,int end){
if(start==end){
tree[node] = arr[start];
return ;
}
int mid = (start+end)/2;
int left_node = 2*node+1;
int right_node = 2*node+2;
build_tree(arr,tree,left_node,start,mid);
build_tree(arr,tree,right_node,mid+1,end);
tree[node] = tree[left_node]+tree[right_node];
}
void update_tree(int arr[],int tree[],int node,int start,int end,int idx,int val){
if(start==end){
arr[idx]=val;
tree[node]=val;
return;
}
int mid = (start+end)/2;
int left_node = 2*node+1;
int right_node = 2*node+2;
if(idx>=start&&idx<=mid) update_tree(arr,tree,left_node,start,mid,idx,val);
else update_tree(arr,tree,right_node,mid+1,end,idx,val);
tree[node]=tree[left_node]+tree[right_node];
}
int query_tree(int arr[],int tree[],int node,int start,int end,int L,int R){
if(R<start||L>end) return 0;
else if(L<=start&&end<=R) return tree[node];
else if(start==end) return tree[node];
int mid = (start+end)/2;
int left_node = 2*node+1;
int right_node = 2*node+2;
int sum_left = query_tree(arr,tree,left_node,start,mid,L,R);
int sum_right = query_tree(arr,tree,right_node,mid+1,end,L,R);
return sum_left+sum_right;
}
using namespace std;
int main()
{
int n,q,l,r;
scanf("%d%d",&n,&q);
for(int i=0;i<n;i++) scanf("%d",&arr[i]);
build_tree(arr,tree,0,0,n-1);
for(int i=0;i<q;i++){
scanf("%d%d",&l,&r);
printf("%d\n",query_tree(arr,tree,0,0,n-1,l,r));
}
return 0;
}
线段树模板【C++】
最新推荐文章于 2024-03-31 11:02:45 发布