You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: src/data_structures/sparse-table.md
+7-7Lines changed: 7 additions & 7 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -32,13 +32,13 @@ The size of the 2-dimensional array will be $\text{MAXN} \times (K + 1)$, where
32
32
$\text{K}$ has to satisfy $\text{K} \ge \lfloor \log_2 \text{MAXN} \rfloor + 1$, because $2^{\lfloor \log_2 \text{MAXN} \rfloor}$ is the biggest power of two range, that we have to support.
33
33
For arrays with reasonable length ($\le 10^7$ elements), $K = 25$ is a good value.
34
34
35
-
```cpp
35
+
```cpp sparsetable_definition
36
36
int st[MAXN][K + 1];
37
37
```
38
38
39
39
Because the range $\[i, i + 2^j - 1\]$ of length $2^j$ splits nicely into the ranges $\[i, i + 2^{j - 1} - 1\]$ and $\[i + 2^{j - 1}, i + 2^j - 1\]$, both of length $2^{j - 1}$, we can generate the table efficiently using dynamic programming:
40
40
41
-
```cpp
41
+
```cpp sparsetable_generation
42
42
for (int i = 0; i < N; i++)
43
43
st[i][0] = f(array[i]);
44
44
@@ -58,7 +58,7 @@ For this type of queries, we want to find the sum of all values in a range.
58
58
Therefore the natural definition of the function $f$ is $f(x, y) = x + y$.
59
59
We can construct the data structure with:
60
60
61
-
```cpp
61
+
```cpp sparsetable_sum_generation
62
62
longlong st[MAXN][K];
63
63
64
64
for (int i = 0; i < N; i++)
@@ -72,7 +72,7 @@ for (int j = 1; j <= K; j++)
72
72
To answer the sum query for the range $\[L, R\]$, we iterate over all powers of two, starting from the biggest one.
73
73
As soon as a power of two $2^j$ is smaller or equal to the length of the range ($= R - L + 1$), we process the first the first part of range $\[L, L + 2^j - 1\]$, and continue with the remaining range $\[L + 2^j, R\]$.
0 commit comments