Here is my Python Solution:
Both parts
with open("input.txt") as f: numbers = [int(x) for x in next(f).split()] class Node(object): def __init__(self, n_childs, n_metadata): self.n_childs = n_childs self.n_metadata = n_metadata self.childs = [] self.metadata = [] it = iter(numbers) root = Node(next(it), next(it)) stack = [] for _ in range(root.n_metadata): stack.append(("metadata", root)) for _ in range(root.n_childs): stack.append(("childs", root)) while stack: inst, current = stack.pop() if inst == "childs": new_node = Node(next(it), next(it)) current.childs.append(new_node) for _ in range(new_node.n_metadata): stack.append(("metadata", new_node)) for _ in range(new_node.n_childs): stack.append(("childs", new_node)) else: current.metadata.append(next(it))
Part 1
def tree_sum(n): return sum(n.metadata)+sum(tree_sum(c) for c in n.childs) print(tree_sum(root))
Part 2
def tree_sum2(n): if len(n.childs) == 0: return sum(n.metadata) else: d = dict((i+1, c) for i, c in enumerate(n.childs)) return sum(tree_sum2(d.get(m, Node(0,0))) for m in n.metadata) print(tree_sum2(root))
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Here is my Python Solution:
Both parts
Part 1
Part 2