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