#!/usr/bin/env python3 import sys from collections import defaultdict rules = defaultdict(set) prints = [] def findbad(pr): all = set(pr) seen = set() for pg in pr: seen.add(pg) for dep in rules[pg]: if dep in all and dep not in seen: return (pg, dep) return None # XXX: this is not efficient or safe, but its late at night # and it works OK (feels like a topographical sort would be better?) def get_ordered(pr): o = [x for x in pr] bad_pg, bad_dep = findbad(o) while bad_pg: pg_i = o.index(bad_pg) dp_i = o.index(bad_dep) o[pg_i] = bad_dep o[dp_i] = bad_pg bad = findbad(o) if bad: bad_pg, bad_dep = bad else: break return o in_rules = True for l in sys.stdin: l = l.strip() if l == "": in_rules = False continue if in_rules: (l, r) = l.split("|") rules[r].add(l) else: prints.append(l.split(",")) tot = 0 for pr in prints: if findbad(pr): o = get_ordered(pr) tot += int(o[int(len(pr)/2)]) print(tot)