adventofcode-2018/08/solve02.py

36 lines
807 B
Python
Raw Normal View History

2018-12-15 15:00:57 +01:00
#!/usr/bin/env python
def read_input():
with open('input.txt', 'r') as f:
data = f.read().splitlines()
return [ int(x) for x in data[0].split(" ")]
def get_node_meta(data, pos):
num_ch = data[pos]
num_m = data[pos+1]
len_ch = 0 # total length of children
values = [0] * num_ch
value = 0
for ch in range(num_ch):
(ch_len, ch_value) = get_node_meta(data, pos+2+len_ch)
len_ch += ch_len
values[ch] = ch_value
meta = data[pos+2+len_ch:pos+2+len_ch+num_m]
# do not have children
if num_ch == 0:
value = sum(meta)
else:
for m in meta:
if m <= num_ch:
value += values[m-1]
return (len_ch+2+num_m, value)
tree = read_input()
(_, value) = get_node_meta(tree, 0)
print(value)