60 lines
1.3 KiB
Python
60 lines
1.3 KiB
Python
|
from lib import *
|
||
|
|
||
|
|
||
|
def parse(fields, i):
|
||
|
n_children = fields[i]
|
||
|
n_meta = fields[i + 1]
|
||
|
i += 2
|
||
|
children = []
|
||
|
meta_score = 0
|
||
|
for _ in range(n_children):
|
||
|
c, i, m = parse(fields, i)
|
||
|
children.append(c)
|
||
|
meta_score += m
|
||
|
for i in range(i, i + n_meta):
|
||
|
meta_score += fields[i]
|
||
|
i += 1
|
||
|
return children, i, meta_score
|
||
|
|
||
|
|
||
|
def parse2(fields, i):
|
||
|
n_children = fields[i]
|
||
|
n_meta = fields[i + 1]
|
||
|
i += 2
|
||
|
children = []
|
||
|
scores = []
|
||
|
for _ in range(n_children):
|
||
|
c, i, s = parse2(fields, i)
|
||
|
children.append(c)
|
||
|
scores.append(s)
|
||
|
|
||
|
score = 0
|
||
|
if n_children == 0:
|
||
|
for j in range(i, i + n_meta):
|
||
|
score += fields[j]
|
||
|
else:
|
||
|
for j in range(i, i + n_meta):
|
||
|
new_i = fields[j]
|
||
|
new_i -= 1
|
||
|
if new_i < 0:
|
||
|
continue
|
||
|
if new_i < len(children):
|
||
|
score += scores[new_i]
|
||
|
i += n_meta
|
||
|
return children, i, score
|
||
|
|
||
|
|
||
|
def main():
|
||
|
input_file = __file__.replace(".py", ".txt")
|
||
|
with open(input_file) as f:
|
||
|
data = f.read()
|
||
|
nums = str_to_ints(data)
|
||
|
tree = parse(nums, 0)
|
||
|
print(tree[2])
|
||
|
tree = parse2(nums, 0)
|
||
|
print(tree[2])
|
||
|
|
||
|
|
||
|
if __name__ == "__main__":
|
||
|
main()
|