# Segment Tree

```
#include &lt;iostream&gt;
#include &lt;cstdio&gt;
#include &lt;cmath&gt;
#include &lt;cstring&gt;
#include &lt;algorithm&gt;
#include &lt;cstdlib&gt;
#include &lt;vector&gt;
#include &lt;sstream&gt;
#include &lt;set&gt;
#include &lt;queue&gt;
#include &lt;stack&gt;
#include &lt;list&gt;
#include &lt;string&gt;
#include &lt;map&gt;

#define ll long long
#define sc scanf
#define pf printf
#define Pi 2*acos(0.0)

#define MAX 1000
using namespace std;

int ara[MAX];
int tree[MAX*3];

void init(int node,int b,int e)
{
if(b==e)
{
tree[node]=ara[b];
return;
}
int mid=(b+e)/2;
int left=2*node;
int right=2*node+1;
init(left,b,mid);
init(right,mid+1,e);
tree[node]=tree[left]+tree[right];
}

int query(int node,int b,int e,int i, int j)
{
if(i&gt;e || j&lt;b)
return 0;
if(b&gt;=i &amp;&amp; e&lt;=j)
return tree[node];
int left=node*2;
int right=node*2+1;
int mid=(b+e)/2;
int p1=query(left,b,mid,i,j);
int p2=query(right,mid+1,e,i,j);
return p1+p2;
}

void update(int node,int b,int e, int i, int new_value)
{
if(i&gt;e || i&lt;b)
return;
if(b&gt;=i &amp;&amp; e&lt;=i)
{
tree[node]=new_value;
return;
}
int left=node*2;
int right=node*2+1;
int mid=(b+e)/2;
update(left,b,mid,i,new_value);
update(right,mid+1,e,i,new_value);
tree[node]=tree[left]+tree[right];
}

int main()
{
freopen(&quot;in.txt&quot;,&quot;r&quot;,stdin);
///freopen(&quot;out.txt&quot;,&quot;w&quot;,stdout);
int n;
cin&gt;&gt;n;
for(int i=1; i&lt;=n; i++)
cin&gt;&gt;ara[i];
init(1,1,n);
cout&lt;&lt;query(1,1,n,1,4)&lt;&lt;endl;
update(1,1,n,2,0);
cout&lt;&lt;query(1,1,n,2,2)&lt;&lt;endl;
update(1,1,n,2,1);
cout&lt;&lt;query(1,1,n,2,3)&lt;&lt;endl;
return 0;
}

```
0 0 votes
Article Rating
Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments