#include<bits/stdc++.h>
using namespace std;
const int maxn=1005;
void build_tree(int arr[],int tree[],int node,int start,int end)
{
if(start==end){
tree[node]=arr[start];
}
else{
int left_node = 2*node+1;
int right_node = 2*node+2;
int mid=(start+end)/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 upate_tree(int arr[],int tree[],int node,int start,int end,int idx,int val)
{
if(start==end)
{
//tree[node]=arr[start];
arr[idx]=val;
tree[node]=val;
}
else
{
int left_node = 2*node+1;
int right_node = 2*node+2;
int mid=(start+end)/2;
if(start<=idx && idx<=mid)
{
upate_tree(arr,tree,left_node,start,mid,idx,val);
}
else
{
upate_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)
{
//打印递归过程
cout<<"start="<<start<<","<<"end="<<end<<'\n';
//求区间[L,R]之间的和
if(R<start || L>end)
{
return 0;
}
else if(L<=start && end<=R){
return tree[node];
}
else if(start==end)
{
return tree[node];
}
else{
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;
}
}
int main()
{ int a[6]= {1,3,5,7,9,11};
int size=6;
int tree[maxn]= {0};
build_tree(a,tree,0,0,size-1);
for(int i=0; i<15; i++)
{
cout<<"tree["<<i<<"]="<<tree[i]<<'\n';
}
cout<<'\n';
upate_tree(a,tree,0,0,size-1,4,6);//将a[4]的值更新为6
// for(int i=0; i<15; i++)
// {
// cout<<"tree["<<i<<"]="<<tree[i]<<'\n';
// }
int s=query_tree(a,tree,0,0,size-1,2,5);//查询区间[2,5]的和
cout<<s<<'\n';
return 0;
}
线段树SegmentTree
最新推荐文章于 2023-11-27 15:48:50 发布