import bisect
import sys
from functools import lru_cache
sys.setrecursionlimit(10**5)
h, w = list(map(int, sys.stdin.readline().split()))
n = int(sys.stdin.readline())
d = list(map(int, sys.stdin.readline().split()))
@lru_cache(maxsize=None)
def go(a, b):
ab = min(a, b)
if ab == 0:
return 0
if ab < d[0]:
return -1
ms = d[bisect.bisect(d, ab)-1]
multia = a // ms
multib = b // ms
dx = a - ms*multia
dy = b - ms*multib
if dx <= dy:
v3 = go(dx, dy)
else:
v3 = go(dy, dx)
if v3 == -1:
return -1
if ms*multib <= dx:
v1 = go(ms*multib, dx)
else:
v1 = go(dx, ms * multib)
if v1 == -1:
return -1
v2 = go(ms*multia, dy)
if v2 == -1:
return -1
return v1 + v2 + v3 + multia*multib
print(go(h, w))
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 | import bisect import sys from functools import lru_cache sys.setrecursionlimit(10**5) h, w = list(map(int, sys.stdin.readline().split())) n = int(sys.stdin.readline()) d = list(map(int, sys.stdin.readline().split())) @lru_cache(maxsize=None) def go(a, b): ab = min(a, b) if ab == 0: return 0 if ab < d[0]: return -1 ms = d[bisect.bisect(d, ab)-1] multia = a // ms multib = b // ms dx = a - ms*multia dy = b - ms*multib if dx <= dy: v3 = go(dx, dy) else: v3 = go(dy, dx) if v3 == -1: return -1 if ms*multib <= dx: v1 = go(ms*multib, dx) else: v1 = go(dx, ms * multib) if v1 == -1: return -1 v2 = go(ms*multia, dy) if v2 == -1: return -1 return v1 + v2 + v3 + multia*multib print(go(h, w)) |
English