File tree 1 file changed +35
-0
lines changed
1 file changed +35
-0
lines changed Original file line number Diff line number Diff line change
1
+ import networkx as nx
2
+
3
+ with open ("input" ) as f :
4
+ gs = f .read ().strip ().split ("\n \n " )
5
+
6
+ rules = [tuple (map (int , l .split ("|" ))) for l in gs [0 ].split ("\n " )]
7
+ updates = [tuple (map (int , l .split ("," ))) for l in gs [1 ].split ("\n " )]
8
+
9
+ unsorted_updates = {
10
+ update
11
+ for update in updates
12
+ if any (
13
+ a in update and b in update and update .index (a ) > update .index (b )
14
+ for a , b in rules
15
+ )
16
+ }
17
+
18
+ # Part 1
19
+ print (
20
+ sum (
21
+ update [len (update ) // 2 ] for update in updates if update not in unsorted_updates
22
+ )
23
+ )
24
+
25
+ # Part 2
26
+ sorted_updates = [
27
+ list (
28
+ nx .topological_sort (
29
+ nx .DiGraph ((a , b ) for a , b in rules if a in update and b in update )
30
+ )
31
+ )
32
+ for update in unsorted_updates
33
+ ]
34
+
35
+ print (sum (update [len (update ) // 2 ] for update in sorted_updates ))
You can’t perform that action at this time.
0 commit comments