@@ -22,21 +22,21 @@ def swap(a: int, b: int) -> tuple[int, int]:
22
22
def create_sparse (max_node : int , parent : list [list [int ]]) -> list [list [int ]]:
23
23
"""
24
24
Create a sparse table that saves each node's 2^i-th parent.
25
-
25
+
26
26
The given ``parent`` table should have the direct parent of each node in row 0.
27
27
This function fills in:
28
-
28
+
29
29
parent[j][i] = parent[j - 1][parent[j - 1][i]]
30
-
30
+
31
31
for each j where 2^j is less than max_node.
32
-
32
+
33
33
For example, consider a small tree where:
34
34
- Node 1 is the root (its parent is 0),
35
35
- Nodes 2 and 3 have parent 1.
36
36
37
37
We set up the parent table for only two levels (row 0 and row 1)
38
38
for max_node = 3. (Note that in practice the table has many rows.)
39
-
39
+
40
40
>>> parent0 = [0, 0, 1, 1] # 0 is unused; node1's parent=0, nodes 2 and 3's parent=1.
41
41
>>> parent1 = [0, 0, 0, 0]
42
42
>>> parent = [parent0, parent1]
@@ -58,11 +58,11 @@ def lowest_common_ancestor(
58
58
"""
59
59
Return the lowest common ancestor (LCA) of nodes u and v in a tree.
60
60
<<<<<<< HEAD
61
-
61
+
62
62
The lists ``level`` and ``parent`` must be precomputed. ``level[i]`` is the depth
63
63
of node i, and ``parent`` is a sparse table where parent[0][i] is the direct parent
64
64
of node i.
65
-
65
+
66
66
=======
67
67
68
68
The lists `level` and `parent` must be precomputed. `level[i]` is the depth of node i,
@@ -107,10 +107,10 @@ def breadth_first_search(
107
107
) -> tuple [list [int ], list [list [int ]]]:
108
108
"""
109
109
Run a breadth-first search (BFS) from the root node of the tree.
110
-
110
+
111
111
This sets each node's direct parent (stored in parent[0]) and calculates the
112
112
depth (level) of each node from the root.
113
-
113
+
114
114
>>> # Consider a simple tree:
115
115
>>> # 1
116
116
>>> # / \\
@@ -141,18 +141,18 @@ def main() -> None:
141
141
"""
142
142
Run a BFS to set node depths and parents in a sample tree, then create the
143
143
sparse table and compute several lowest common ancestors.
144
-
144
+
145
145
The sample tree used is:
146
146
<<<<<<< HEAD
147
-
147
+
148
148
1
149
- / | \
149
+ / | \
150
150
2 3 4
151
151
/ / \\ \\
152
152
5 6 7 8
153
153
/ \\ | / \\
154
154
9 10 11 12 13
155
-
155
+
156
156
=======
157
157
158
158
1
@@ -171,7 +171,7 @@ def main() -> None:
171
171
- LCA(6, 7) --> 3
172
172
- LCA(4, 12) --> 4
173
173
- LCA(8, 8) --> 8
174
-
174
+
175
175
To test main() without it printing to the console, we capture the output.
176
176
177
177
>>> import sys
0 commit comments