-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday7.py
50 lines (47 loc) · 1.38 KB
/
day7.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
from heapq import *
def part1(src):
s = 0
for line in src.splitlines():
m, ns = line.split(": ")
m = int(m)
ns = list(map(int, ns.split(" ")))
fn = ns[0]
stack = [(m, len(ns) - 1)]
while stack:
mc, i = heappop(stack)
n = ns[i]
if i == 0:
if n == mc:
s += m
break
continue
if (mcn := mc - n) >= fn:
heappush(stack, (mcn, i - 1))
if mc % n == 0:
heappush(stack, (mc // n, i - 1))
return s
def part2(src):
s = 0
for line in src.splitlines():
m, ns = line.split(": ")
m = int(m)
ns = list(map(int, ns.split(" ")))
fn = ns[0]
stack = [(m, len(ns) - 1)]
while stack:
mc, i = heappop(stack)
n = ns[i]
if i == 0:
if n == mc:
s += m
break
continue
mcs = str(mc)
nstr = str(n)
if mcs != nstr and mcs.endswith(nstr):
heappush(stack, (int(mcs[:len(mcs) - len(nstr)]), i - 1))
if (mcn := mc - n) >= fn:
heappush(stack, (mcn, i - 1))
if mc % n == 0 and (mcn := mc // n) >= fn:
heappush(stack, (mc // n, i - 1))
return s