34 lines
770 B
Python
34 lines
770 B
Python
import fileinput
|
|
import math
|
|
|
|
input = fileinput.input()
|
|
|
|
instructions = next(input).strip()
|
|
next(input)
|
|
|
|
tree = {}
|
|
|
|
for line in input:
|
|
if line.strip():
|
|
(parent, children) = line.split(" = ")
|
|
(left, right) = children[1:-2].split(", ")
|
|
tree[parent] = (left, right)
|
|
|
|
nodes = [node for node in tree if node[2] == "A"]
|
|
cycles = [0] * len(nodes)
|
|
|
|
for i in range(len(nodes)):
|
|
while nodes[i][2] != "Z":
|
|
for instr in instructions:
|
|
cycles[i] += 1
|
|
if instr == "L":
|
|
(nodes[i], _) = tree[nodes[i]]
|
|
else:
|
|
(_, nodes[i]) = tree[nodes[i]]
|
|
if nodes[i][2] == "Z":
|
|
break
|
|
|
|
part1 = cycles[nodes.index("ZZZ")]
|
|
part2 = math.lcm(*cycles)
|
|
|
|
print(part1, part2)
|