# pyright: strict import math from collections.abc import Callable from itertools import cycle from sys import stdin instructions, tree = stdin.read().rstrip("\n").split("\n\n") nodes: dict[str, tuple[str, str]] = dict() for n in tree.split("\n"): k, v = n.split(" = ") l, r = v.strip("()").split(", ") nodes[k] = (l, r) def solve( nodes: dict[str, tuple[str, str]], start: str, end_cond: Callable[[str], bool], instructions: str, ) -> int: current = start for n, ins in enumerate(cycle(instructions)): if end_cond(current): return n current = nodes[current][0 if ins == "L" else 1] return 0 print(solve(nodes, "AAA", lambda c: c == "ZZZ", instructions)) print( math.lcm( *( solve(nodes, s, lambda c: c.endswith("Z"), instructions) for s in nodes.keys() if s.endswith("A") ) ) )