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.
57 lines
1.2 KiB
Python
57 lines
1.2 KiB
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)
|
|
|
|
@property
|
|
def value(self):
|
|
if len(self.children) == 0:
|
|
return sum(self.meta)
|
|
|
|
val = 0
|
|
for ref in self.meta:
|
|
if ref > 0 and ref <= len(self.children):
|
|
val += self.children[ref - 1].value
|
|
return val
|
|
|
|
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.value)
|
|
|