You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

49 lines
1003 B
Python

import sys
from collections import defaultdict
# sys.setrecursionlimit(6500)
with open('input.txt', 'r') as f:
numbers = [int(x) for x in f.read().split()]
# print(numbers)
class Node:
def __init__(self, header):
self.header = header
self.children = []
self.meta = []
def add_child(self, child):
self.children.append(child)
def add_meta(self, data):
self.meta.append(data)
def meta_sum(self):
return sum([x.meta_sum() for x in self.children]) + sum(self.meta)
def get_node(i):
num_childs = numbers[i]
num_meta = numbers[i + 1]
header = (num_childs, num_meta)
node = Node(header)
size = 2
for _ in range(num_childs):
child, ch_size = get_node(i + size)
node.add_child(child)
size += ch_size
for _ in range(num_meta):
node.add_meta(numbers[i + size])
size += 1
return node, size
# print(len(numbers))
root = get_node(0)[0]
print(root.meta_sum())