Segment tree implementation
This commit is contained in:
parent
3fb9b598ae
commit
9da26930f3
10
luku28.tex
10
luku28.tex
|
@ -37,8 +37,8 @@ Using this approach, the function becomes as follows:
|
||||||
int sum(int a, int b, int k, int x, int y) {
|
int sum(int a, int b, int k, int x, int y) {
|
||||||
if (b < x || a > y) return 0;
|
if (b < x || a > y) return 0;
|
||||||
if (a <= x && y <= b) return p[k];
|
if (a <= x && y <= b) return p[k];
|
||||||
int d = (y-x+1)/2;
|
int d = (x+y)/2;
|
||||||
return sum(a,b,2*k,x,x+d-1) + sum(a,b,2*k+1,x+d,y);
|
return sum(a,b,2*k,x,d) + sum(a,b,2*k+1,d+1,y);
|
||||||
}
|
}
|
||||||
\end{lstlisting}
|
\end{lstlisting}
|
||||||
Now we can calculate the sum of
|
Now we can calculate the sum of
|
||||||
|
@ -63,9 +63,9 @@ the sum can be found in \texttt{p}.
|
||||||
If $[x,y]$ is partially inside $[a,b]$,
|
If $[x,y]$ is partially inside $[a,b]$,
|
||||||
the search continues recursively to the
|
the search continues recursively to the
|
||||||
left and right half of $[x,y]$.
|
left and right half of $[x,y]$.
|
||||||
The size of both halves is $d=\frac{1}{2}(y-x+1)$;
|
The left half is $[x,d]$
|
||||||
the left half is $[x,x+d-1]$
|
and the right half is $[d+1,y]$
|
||||||
and the right half is $[x+d,y]$.
|
where $d=\lfloor \frac{x+y}{2} \rfloor$.
|
||||||
\end{samepage}
|
\end{samepage}
|
||||||
|
|
||||||
The following picture shows how the search proceeds
|
The following picture shows how the search proceeds
|
||||||
|
|
Loading…
Reference in New Issue