File tree Expand file tree Collapse file tree 1 file changed +54
-0
lines changed Expand file tree Collapse file tree 1 file changed +54
-0
lines changed Original file line number Diff line number Diff line change
1
+ import collections
2
+ import math
3
+ import re
4
+ import sys
5
+
6
+ decks = [l .rstrip ('\n ' ) for l in sys .stdin .read ().split ('\n \n ' )]
7
+ decks = [[int (i ) for i in re .findall (r'(?<=\n)(\d+)' , l )] for l in decks ]
8
+
9
+ a , b = decks
10
+ a = collections .deque (a )
11
+ b = collections .deque (b )
12
+
13
+ # part 1:
14
+ # while a and b:
15
+ # aa = a.popleft()
16
+ # bb = b.popleft()
17
+ # if aa > bb:
18
+ # winner = a
19
+ # elif bb > aa:
20
+ # winner = b
21
+ # else:
22
+ # assert False, aa
23
+ # winner.append(max(aa, bb))
24
+ # winner.append(min(aa, bb))
25
+ # winner = a or b
26
+
27
+ def combat (a , b ):
28
+ seen = set ()
29
+ while a and b :
30
+ kk = (tuple (a ), tuple (b ))
31
+ if kk in seen :
32
+ return 1 , a
33
+ seen .add (kk )
34
+ aa = a .popleft ()
35
+ bb = b .popleft ()
36
+ if len (a ) >= aa and len (b ) >= bb :
37
+ winnum , _ = combat (
38
+ collections .deque (list (a )[:aa ]),
39
+ collections .deque (list (b )[:bb ]),
40
+ )
41
+ winner = a if winnum == 1 else b
42
+ else :
43
+ if aa > bb :
44
+ winner = a
45
+ elif bb > aa :
46
+ winner = b
47
+ else :
48
+ assert False , aa
49
+ winner .append (aa if winner is a else bb )
50
+ winner .append (aa if winner is not a else bb )
51
+ return 1 if winner is a else 2 , winner
52
+ winnum , winner = combat (a , b )
53
+
54
+ print (sum (i * v for i , v in enumerate (reversed (winner ), 1 )))
You can’t perform that action at this time.
0 commit comments