diff --git a/segment tree.txt b/segment tree.txt new file mode 100644 index 00000000..68fc7387 --- /dev/null +++ b/segment tree.txt @@ -0,0 +1,470 @@ + +
+ + + + + + + + + + + + + + + + + + + + + + + + +x
using namespace std;
int tree[10000];
int arr[10000];
void update_tree(int node, int index, int st, int en, int val){
if(st==en && index==st){
tree[node]=val;
return;
}
int mid=(st+en)/2;
if(index<=mid)
update_tree(2*node, index, st, mid,val);
else
update_tree(2*node+1, index, mid+1, en,val);
tree[node]=tree[2*node]+tree[2*node+1];
}
int query_tree(int node,int qst,int qen,int st,int en)
{
if(qst<=st && qen>=en){
return tree[node];
}
if(qen<st || qst>en){
return 0;
}
int mid=(st+en)/2;
int l_arr=query_tree(2*node,qst,qen,st,mid);
int r_arr=query_tree(2*node+1,qst,qen,mid+1,en);
return l_arr+r_arr;
}
int build_tree(int node, int st, int en){
//terminating condition
if(st==en){
tree[node]=arr[st];
return tree[node];
}
int mid=(st+en)/2;
int l_sum=build_tree(2*node,st,mid);
int r_sum=build_tree(2*node+1,mid+1,en);
tree[node] = l_sum + r_sum;
return tree[node];