From d48ae544a98bc5bc3d07e70b0e7e2c65dc360da6 Mon Sep 17 00:00:00 2001 From: Chau Long Do Date: Wed, 4 May 2022 11:38:06 +0700 Subject: [PATCH 1/2] Create tree_height.py --- .../2_tree_height.py/tree_height.py | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 2. Data Structures/2_tree_height.py/tree_height.py diff --git a/2. Data Structures/2_tree_height.py/tree_height.py b/2. Data Structures/2_tree_height.py/tree_height.py new file mode 100644 index 0000000..aa3b41a --- /dev/null +++ b/2. Data Structures/2_tree_height.py/tree_height.py @@ -0,0 +1,34 @@ +# python3 + +import sys +import threading +import collections +import collections + +def compute_height(n, parents): + # Replace this code with a faster implementation + max_height = -1 + tree = collections.defaultdict(list) + q = collections.deque([-1]) + for i, node in enumerate(parents): + tree[node].append(i) + while q: + max_height += 1 + l = len(q) + for _ in range(l): + node = q.popleft() + q.extend(tree[node]) + return max_height + +def main(): + n = int(input()) + parents = list(map(int, input().split())) + print(compute_height(n, parents)) + + +# In Python, the default limit on recursion depth is rather low, +# so raise it here for this problem. Note that to take advantage +# of bigger stack, we have to launch the computation in a new thread. +sys.setrecursionlimit(10**7) # max depth of recursion +threading.stack_size(2**27) # new thread will get stack of such size +threading.Thread(target=main).start() From ff00f8792b4f2a39c825a5b996a4e6b1f2c330eb Mon Sep 17 00:00:00 2001 From: Chau Long Do Date: Wed, 4 May 2022 11:39:22 +0700 Subject: [PATCH 2/2] Update tree_height.py --- 2. Data Structures/2_tree_height.py/tree_height.py | 1 - 1 file changed, 1 deletion(-) diff --git a/2. Data Structures/2_tree_height.py/tree_height.py b/2. Data Structures/2_tree_height.py/tree_height.py index aa3b41a..b21cfdf 100644 --- a/2. Data Structures/2_tree_height.py/tree_height.py +++ b/2. Data Structures/2_tree_height.py/tree_height.py @@ -3,7 +3,6 @@ import sys import threading import collections -import collections def compute_height(n, parents): # Replace this code with a faster implementation