-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathday05.py
executable file
·76 lines (53 loc) · 1.22 KB
/
day05.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#!/usr/bin/env python3
from utils.all import *
advent.setup(2024, 5)
fin = advent.get_input()
data = fin.read()
ans1 = ans2 = 0
def check(g, nodes):
idx = dict((x, i) for i, x in enumerate(nodes))
for x in nodes:
for nxt in g[x]:
if nxt in idx and idx[nxt] < idx[x]:
return False
return True
def middle(g, nodes):
last = None
seen = set()
nodes = set(nodes)
for _ in range(len(nodes) // 2 + 1):
for x in nodes:
for other in nodes:
if other == x:
continue
# if other should come before x it's wrong
if x in g[other]:
break
else:
last = x
seen.add(x)
nodes.remove(x)
break
assert last is not None
return last
sec = data.split('\n\n')
g = defaultdict(set)
for line in sec[0].splitlines():
a, b = map(int, line.split('|'))
g[a].add(b)
# dump_dict(g)
good_lines = set()
for i, line in enumerate(sec[1].splitlines()):
lst = list(map(int, line.split(',')))
if check(g, lst):
assert len(lst) % 2 == 1
ans1 += lst[len(lst) // 2]
good_lines.add(i)
# 10683 wrong
advent.print_answer(1, ans1)
for i, line in enumerate(sec[1].splitlines()):
if i in good_lines:
continue
nodes = list(map(int, line.split(',')))
ans2 += middle(g, nodes)
advent.print_answer(2, ans2)