55 lines
1.1 KiB
Python
55 lines
1.1 KiB
Python
""" day 5 part 1 """
|
|
|
|
import fileinput
|
|
import collections
|
|
|
|
deps = collections.defaultdict(set) # map post -> [pre]
|
|
|
|
reader = fileinput.input()
|
|
|
|
for line in reader:
|
|
line = line.strip()
|
|
if not line:
|
|
break
|
|
|
|
pre,post = line.split('|')
|
|
deps[post].add(pre)
|
|
|
|
total = 0
|
|
|
|
def print_page(seq, page, deps, printed, wanted):
|
|
if page in printed:
|
|
return
|
|
for dep in deps[page]:
|
|
if dep in wanted:
|
|
print_page(seq, dep, deps, printed, wanted)
|
|
seq.append(page)
|
|
printed.add(page)
|
|
|
|
for line in reader:
|
|
seq = line.strip().split(',')
|
|
wanted = set(seq)
|
|
|
|
seen = set()
|
|
safe = True
|
|
for page in seq:
|
|
# print(f'{seen} -> {page}')
|
|
for dep in deps[page]:
|
|
if dep in wanted and dep not in seen:
|
|
# print(f' {page} missing {dep}')
|
|
safe = False
|
|
seen.add(page)
|
|
|
|
if not safe:
|
|
seq = []
|
|
printed = set()
|
|
for page in wanted:
|
|
print_page(seq, page, deps, printed, wanted)
|
|
val = int(seq[len(seq)//2])
|
|
print(f'{seq} -> {val}')
|
|
|
|
total += int(val)
|
|
|
|
print(total)
|
|
|