Problem:
 Score : 400 points    Problem Statement Dolphin is planning to generate a small amount of a certain chemical substance C. In order to generate the substance C, he must prepare a solution which is a mixture of two substances A and B in the ratio of M_a:M_b . He does not have any stock of chemicals, however, so he will purchase some chemicals at a local pharmacy. The pharmacy sells N kinds of chemicals. For each kind of chemical, there is exactly one package of that chemical in stock. The package of chemical i contains a_i grams of the substance A and b_i grams of the substance B, and is sold for c_i yen (the currency of Japan). Dolphin will purchase some of these packages. For some reason, he must use all contents of the purchased packages to generate the substance C. Find the minimum amount of money required to generate the substance C. If it is not possible to generate the substance C by purchasing any combination of packages at the pharmacy, report that fact.      Constraints  1≦N≦40   1≦a_i,b_i≦10   1≦c_i≦100   1≦M_a,M_b≦10   gcd(M_a,M_b)=1  a_i , b_i , c_i , M_a and M_b are integers.         Input The input is given from Standard Input in the following format:  N  M_a  M_b  a_1  b_1  c_1  a_2  b_2  c_2  :  a_N  b_N  c_N       Output Print the minimum amount of money required to generate the substance C. If it is not possible to generate the substance C, print -1 instead.        Sample Input 1 3 1 1
1 2 1
2 1 2
3 3 10      Sample Output 1 3  The amount of money spent will be minimized by purchasing the packages of chemicals 1 and 2 . In this case, the mixture of the purchased chemicals will contain 3 grams of the substance A and 3 grams of the substance B, which are in the desired ratio: 3:3=1:1 . The total price of these packages is 3 yen.       Sample Input 2 1 1 10
10 10 10      Sample Output 2 -1  The ratio 1:10 of the two substances A and B cannot be satisfied by purchasing any combination of the packages. Thus, the output should be -1 .

Solution (Python):
n,ma,mb = map(int,input().split())
l = []
sum_a = 0
sum_b = 0
for _ in range(n):
    a,b,c = map(int,input().split())
    sum_a += a
    sum_b += b
    l.append([a,b,c])

INF = 10**10
dp = list( list([INF for i in range(450)] for i in range(450)) for i in range(45))
dp[0][0][0] = 0
for i in range(n):
    for s in range(sum_a+1):
        for k in range(sum_b+1):
            a,b,c = l[i]
            dp[i+1][s][k] = min(dp[i][s][k], dp[i+1][s][k],dp[i][s-a][k-b]+c)

ans = 10**10
k = 1
while ma*k < 450 and mb*k < 450 :
    ans = min(ans, dp[n][ma*k][mb*k])
    k += 1
if ans != 10**10:
  print(ans)
else:
  print(-1)

Solution (Python):
n,ma,mb = map(int,input().split())
l = []
sum_a = 0
sum_b = 0
for _ in range(n):
    a,b,c = map(int,input().split())
    sum_a += a
    sum_b += b
    l.append([a,b,c])

INF = 10**10
dp = list( list([INF for i in range(450)] for i in range(450)) for i in range(45))
dp[0][0][0] = 0
for i in range(n):
    for s in range(sum_a+1):
        for k in range(sum_b+1):
            a,b,c = l[i]
            dp[i+1][s][k] = min(dp[i][s][k], dp[i+1][s][k],dp[i][s-a][k-b]+c)

ans = 10**10
k = 1
while ma*k < 450 and mb*k < 450 :
    ans = min(ans, dp[n][ma*k][mb*k])
    k += 1
if ans != 10**10:
  print(ans)
else:
  print(-1)

Solution (Python):
n,ma,mb=map(int,input().split())
zen=[[10**10]*401 for i in range(401)]
kou=[[10**10]*401 for j in range(401)]
A=[ list(map(int,input().split())) for i in range(n//2)];a=len(A)
B=[ list(map(int,input().split())) for i in range(n-n//2)];b=len(B)
for bit in range(1<<a):
    now=[0,0,0]
    for i in range(a):
        if (bit>>i)&1:
            now[0]+=A[i][0]
            now[1]+=A[i][1]
            now[2]+=A[i][2]
    zen[now[0]][now[1]]=min(zen[now[0]][now[1]],now[2])
for bit in range(1<<b):
    now=[0,0,0]
    for i in range(b):
        if (bit>>i)&1:
            now[0]+=B[i][0]
            now[1]+=B[i][1]
            now[2]+=B[i][2]
    kou[now[0]][now[1]]=min(kou[now[0]][now[1]],now[2])


ans=10**10
for base in range(1,401):
    na=base*ma ; nb=base*mb 
    if max(na,nb)>400: break
    for i in range(na+1):
        for j in range(nb+1):
            ans=min(ans,zen[i][j]+ kou[na-i][nb-j])


print(ans if ans<10**6 else -1)

Solution (Python):









n, a_ratio, b_ratio = list(map(int, input().split()))
chemicals = [list(map(int, input().split())) for _ in range(n)]

inf = 10 ** 10
ab_max = 10
dp = [[[inf for j in range(n * ab_max + 1)] for i in range(n * ab_max + 1)] for k in range(n)]

dp[0][0][0] = 0
dp[0][chemicals[0][0]][chemicals[0][1]] = chemicals[0][2]

for k in range(1, n):
    for i in range(n * ab_max + 1):
        for j in range(n * ab_max + 1):
            if i-chemicals[k][0] >= 0 and j-chemicals[k][1] >= 0:
                dp[k][i][j] = min(dp[k-1][i][j],  dp[k-1][i-chemicals[k][0]][j-chemicals[k][1]] + chemicals[k][2])
            else:
                dp[k][i][j] = dp[k-1][i][j]

ans = inf
bai = 1
while(a_ratio * bai <= n * ab_max and b_ratio * bai <= n * ab_max):
    ans = min(ans, dp[n-1][a_ratio * bai][b_ratio * bai])
    bai += 1

if ans < inf:
    print(ans)
else:
    print(-1)

Solution (Python):
from copy import deepcopy

def getval():
    n,ma,mb = map(int,input().split())
    p = [list(map(int,input().split())) for i in range(n)]
    return n,ma,mb,p 

def main(n,ma,mb,p):
    dp = [[[-1 for i in range(401)] for i in range(401)]]
    dp[0][0][0] = 0
    for i in range(n):
        temp = deepcopy(dp[-1])
        temp[0][0] = 0
        cur = p[i]
        prev = dp[-1]
        for a in range(401):
            for b in range(401):
                if cur[0]>a or cur[1]>b:
                    continue
                if prev[a-cur[0]][b-cur[1]]==-1:
                    continue
                elif prev[a][b]==-1:
                    temp[a][b] = prev[a-cur[0]][b-cur[1]] + cur[2]
                    
                else:
                    temp[a][b] = min(prev[a][b], prev[a-cur[0]][b-cur[1]] + cur[2])
        dp.append(temp)
    ans = -1
    for i in range(1,401):
        if i*ma>400 or i*mb>400:
            break
        if dp[n][i*ma][i*mb]!=-1:
            if ans==-1:
                ans = dp[n][i*ma][i*mb]
            else:
                ans = min(ans,dp[n][i*ma][i*mb])
    print(ans)
    

if __name__=="__main__":
    n,ma,mb,p = getval()
    main(n,ma,mb,p)

Solution (Python):



import sys
readline = sys.stdin.readline

N,Ma,Mb = map(int,readline().split())
INF = 10 ** 10
dp = [[INF] * (401) for i in range(401)]
dp[0][0] = 0

for _ in range(N):
  a,b,c = map(int,readline().split())
  for i in range(len(dp) - 1, -1, -1):
    for j in range(len(dp[i]) - 1, -1, -1):
      if dp[i][j] == INF:
        continue
      if dp[i + a][j + b] > dp[i][j] + c:
        dp[i + a][j + b] = dp[i][j] + c

ans = INF
import math
for i in range(1, len(dp)):
  for j in range(1, len(dp)):
    g = math.gcd(i,j)
    if i // g == Ma and j // g == Mb:
      if ans > dp[i][j]:
        ans = dp[i][j]
      
if ans == INF:
  print(-1)
else:
  print(ans)

Solution (Python):



import sys
readline = sys.stdin.readline

N,Ma,Mb = map(int,readline().split())
INF = 10 ** 10
dp = [[INF] * (401) for i in range(401)]
dp[0][0] = 0

for _ in range(N):
  a,b,c = map(int,readline().split())
  for i in range(len(dp) - 1, -1, -1):
    for j in range(len(dp[i]) - 1, -1, -1):
      if dp[i][j] == INF:
        continue
      dp[i + a][j + b] = min(dp[i + a][j + b], dp[i][j] + c)

ans = INF
import math
for i in range(1, len(dp)):
  for j in range(1, len(dp)):
    g = math.gcd(i,j)
    if i // g == Ma and j // g == Mb:
      if ans > dp[i][j]:
        ans = dp[i][j]
      
if ans == INF:
  print(-1)
else:
  print(ans)

Solution (Python):
N, Ma, Mb = map(int, input().split())
L = []
sum_a = 0
sum_b = 0
for _ in range(N):
    a, b, c = map(int, input().split())
    sum_a += a
    sum_b += b
    L.append((a, b, c))

inf = 10 ** 9 + 7
dp = [[[inf] * (sum_b + 1) for _ in range(sum_a + 1)] for _ in range(N + 1)]

dp[0][0][0] = 0
for i in range(N):
    for a in range(sum_a + 1):
        for b in range(sum_b + 1):
            if 0 <= a - L[i][0] and 0 <= b - L[i][1]:
                
                dp[i + 1][a][b] = min(dp[i][a - L[i][0]]
                                      [b - L[i][1]] + L[i][2], dp[i][a][b])
            else:
                dp[i + 1][a][b] = dp[i][a][b]

min_cost = inf
for a in range(sum_a + 1):
    for b in range(sum_b + 1):
        if a * Mb == b * Ma and dp[N][a][b] != 0:
            
            min_cost = min(dp[N][a][b], min_cost)

print(min_cost if min_cost != inf else -1)

Solution (Python):
N, Ma, Mb = map(int, input().split())
L = []
sum_a = 0
sum_b = 0
for _ in range(N):
    a, b, c = map(int, input().split())
    sum_a += a
    sum_b += b
    L.append((a, b, c))

inf = 10 ** 9 + 7
dp = [[[inf] * (sum_b + 1) for _ in range(sum_a + 1)] for _ in range(N + 1)]

dp[0][0][0] = 0
for i in range(N):
    for a in range(sum_a + 1):
        for b in range(sum_b + 1):
            if 0 <= a - L[i][0] and 0 <= b - L[i][1]:
                
                dp[i + 1][a][b] = min(dp[i][a - L[i][0]]
                                      [b - L[i][1]] + L[i][2], dp[i][a][b])
            else:
                dp[i + 1][a][b] = dp[i][a][b]

min_cost = inf
for a in range(sum_a + 1):
    for b in range(sum_b + 1):
        if a * Mb == b * Ma and dp[N][a][b] != 0:
            
            min_cost = min(dp[N][a][b], min_cost)

print(min_cost if min_cost != inf else -1)

Solution (Python):
N,Ma,Mb=map(int, input().split())
A = []
B = []
C = []
for i in range(N):
  a,b,c=map(int, input().split())
  A.append(a)
  B.append(b)
  C.append(c)
sa = sum(A)
sb = sum(B)

dp = [[[10000]*(sb+1) for _ in range(sa+1)] for _ in range(N+1)]
dp[0][0][0] = 0

ta = 0
tb = 0
for i in range(N):
  a = A[i]
  b = B[i]
  for j in range(sa):
    for k in range(sb):
      if j - a >= 0 and k - b >= 0:
        dp[i+1][j][k] = min(dp[i][j-a][k-b]+C[i], dp[i][j][k])
      else:
        dp[i+1][j][k] = min(dp[i+1][j][k], dp[i][j][k])

ans = 10000
for i in range(1, sa+1):
  for j in range(1, sb+1):
    if Ma * j == Mb * i:
      ans = min(ans, dp[N][i][j])
if ans == 10000:
  ans = -1
print(ans)

Solution (Python):
N, Ma, Mb = map(int, input().split())

sum_a = 0
sum_b = 0
A = []
B = []
C = []
for _ in range(N):
    a, b, c = map(int, input().split())
    sum_a += a
    sum_b += b
    A.append(a)
    B.append(b)
    C.append(c)

inf = 10 ** 9 + 7

dp = [[[inf] * (sum_b + 1) for _ in range(sum_a + 1)] for _ in range(N + 1)]

dp[0][0][0] = 0
for i in range(N):
    for sa in range(sum_a):
        for sb in range(sum_b):
            if sa - A[i] >= 0 and sb - B[i] >= 0:
                dp[i + 1][sa][sb] = min(dp[i][sa - A[i]]
                                        [sb - B[i]] + C[i], dp[i][sa][sb])
            else:
                dp[i + 1][sa][sb] = min(dp[i][sa][sb], dp[i + 1][sa][sb])

ans = inf
for i in range(1, sum_a + 1):
    for j in range(1, sum_b + 1):
        if Ma * j == Mb * i:
            ans = min(ans, dp[N][i][j])

print(ans if ans != inf else -1)

Solution (Python):
N, Ma, Mb = map(int, input().split())
abc = [list(map(int, input().split())) for _ in range(N)]
INF = 10 ** 9 + 7
dp = [[[INF] * (Mb * N + 1) for _ in range(N * Ma + 1)] for _ in range(N + 1)]
dp[0][0][0] = 0
for i in range(N):
    for j in range(Ma * N + 1):
        for k in range(Mb * N + 1):
            if j - abc[i][0] >= 0 and k - abc[i][1] >=0:
                dp[i + 1][j][k] = min(dp[i][j - abc[i][0]][k - abc[i][1]] + abc[i][2], dp[i][j][k])
            else:
                dp[i + 1][j][k] = min(dp[i][j][k], dp[i + 1][j][k])

ans = INF
for i in range(1, Ma * N + 1):
    for j in range(1, Mb * N + 1):
        if Ma * j == Mb * i:
            ans = min(ans, dp[N][i][j])

print(ans if ans != INF else -1)

Solution (Python):
n,ma,mb=map(int,input().split())
dp=[[[10**4 for _ in range(401)] for __ in range(401)] for ___ in range(n+1)]
for i in range(n+1):
    dp[i][0][0]=0
for i in range(n):
    a,b,c=map(int,input().split())
    for j in range(401):
        for k in range(401):
            if j>=a and k>=b:
            	dp[i+1][j][k]=min(dp[i][j][k],dp[i][j-a][k-b]+c)
            else:
                dp[i+1][j][k]=dp[i][j][k]
ans=float("INF")
for j in range(1,401):
    for k in range(1,401):
        if ma*k==mb*j:
            ans=min(ans,dp[n][j][k])
if ans==10**4:
    print(-1)
else:
    print(ans)

Solution (Python):
n, ma, mb = (int(x) for x in input().split())
ABC = [tuple(int(x) for x in input().split()) for _ in range(n)]
D1 = dict()
D2 = dict()
for (m, D, j) in ((n // 2, D1, 0), (n - n // 2, D2, n // 2)):
    for bit in range(1, 1<<m):
        sum_a = 0
        sum_b = 0
        sum_c = 0
        for i in range(m):
            if bit & 1<<i:
                a, b, c = ABC[i + j]
                sum_a += a
                sum_b += b
                sum_c += c
        s = mb * sum_a - ma * sum_b
        if s in D:
            D[s] = min(D[s], sum_c)
        else:
            D[s] = sum_c
ans = 10**18
if 0 in D1:
    ans = min(ans, D1[0])
if 0 in D2:
    ans = min(ans, D2[0])
for s in D1:
    if -s in D2:
        ans = min(ans, D1[s] + D2[-s])
if ans == 10**18:
    print(-1)
else:
    print(ans)

Solution (Python):
n, ma, mb = (int(x) for x in input().split())
ABC = [tuple(int(x) for x in input().split()) for _ in range(n)]
m = n // 2
D = dict()
E = dict()
for bit in range(1, 1<<m):
    sum_a = 0
    sum_b = 0
    sum_c = 0
    for i in range(m):
        if bit & 1<<i:
            a, b, c = ABC[i]
            sum_a += a
            sum_b += b
            sum_c += c
    s = mb * sum_a - ma * sum_b
    if s in D:
        D[s] = min(D[s], sum_c)
    else:
        D[s] = sum_c

k = n - m
for bit in range(1, 1<<k):
    sum_a = 0
    sum_b = 0
    sum_c = 0
    for i in range(k):
        if bit & 1<<i:
            a, b, c = ABC[m + i]
            sum_a += a
            sum_b += b
            sum_c += c
    s = mb * sum_a - ma * sum_b
    if s in E:
        E[s] = min(E[s], sum_c)
    else:
        E[s] = sum_c

ans = 10**18
if 0 in D:
    ans = min(ans, D[0])
if 0 in E:
    ans = min(ans, E[0])
for s, c in D.items():
    if -s in E:
        ans = min(ans, D[s] + E[-s])
if ans == 10**18:
    print(-1)
else:
    print(ans)

Solution (Python):
from fractions import Fraction
import sys
input = sys.stdin.readline

INF = float('inf')

N,A,B = list(map(int,input().split()))
data = [list(map(int, input().split())) for _ in range(N)]

P = []
M = []
Z = []
for a,b,c in data:
  if Fraction(a,b) == Fraction(A,B):
    Z.append(c)
  elif Fraction(a,b) > Fraction(A,B):
    P.append((a*2520-b*2520*A//B,c))
  else:
    M.append((-a*2520+b*2520*A//B,c))
    
dpP = [INF for i in range(1000000)]
dpP[0] = 0
for v,c in P:
  for i in range(1000000)[::-1]:
    if i>=v:
      dpP[i] = min(dpP[i],dpP[i-v]+c)

dpM = [INF for i in range(1000000)]
dpM[0] = 0
for v,c in M:
  for i in range(1000000)[::-1]:
    if i>=v:
      dpM[i] = min(dpM[i],dpM[i-v]+c)
      
ans = INF
if Z:
  ans = min(Z)
for i in range(1,1000000):
  ans = min(ans,dpP[i]+dpM[i])

if ans == INF:
  print(-1)
else:
  print(ans)

Solution (Python):






import sys
input = sys.stdin.readline

import math

import bisect
import heapq
from collections import defaultdict
from collections import deque
from collections import Counter
from functools import lru_cache





MOD = 10**9+7
INF = float('inf')
AZ = "abcdefghijklmnopqrstuvwxyz"






def I(): return int(input().strip())
def S(): return input().strip()
def IL(): return list(map(int,input().split()))
def SL(): return list(map(str,input().split()))
def ILs(n): return list(int(input()) for _ in range(n))
def SLs(n): return list(input().strip() for _ in range(n))
def ILL(n): return [list(map(int, input().split())) for _ in range(n)]
def SLL(n): return [list(map(str, input().split())) for _ in range(n)]



def DD(arg): return defaultdict(arg)


def inv(n): return pow(n, MOD-2, MOD)


kaijo_memo = []
def kaijo(n):
  if(len(kaijo_memo) > n): return kaijo_memo[n]
  if(len(kaijo_memo) == 0): kaijo_memo.append(1)
  while(len(kaijo_memo) <= n): kaijo_memo.append(kaijo_memo[-1] * len(kaijo_memo) % MOD)
  return kaijo_memo[n]

gyaku_kaijo_memo = []
def gyaku_kaijo(n):
  if(len(gyaku_kaijo_memo) > n): return gyaku_kaijo_memo[n]
  if(len(gyaku_kaijo_memo) == 0): gyaku_kaijo_memo.append(1)
  while(len(gyaku_kaijo_memo) <= n): gyaku_kaijo_memo.append(gyaku_kaijo_memo[-1] * pow(len(gyaku_kaijo_memo),MOD-2,MOD) % MOD)
  return gyaku_kaijo_memo[n]

def nCr(n,r):
  if n == r: return 1
  if n < r or r < 0: return 0
  ret = 1
  ret = ret * kaijo(n) % MOD
  ret = ret * gyaku_kaijo(r) % MOD
  ret = ret * gyaku_kaijo(n-r) % MOD
  return ret


def factorization(n):
  arr = []
  temp = n
  for i in range(2, int(-(-n**0.5//1))+1):
    if temp%i==0:
      cnt=0
      while temp%i==0: 
        cnt+=1 
        temp //= i
      arr.append([i, cnt])
  if temp!=1: arr.append([temp, 1])
  if arr==[]: arr.append([n, 1])
  return arr


def make_divisors(n):
  divisors = []
  for i in range(1, int(n**0.5)+1):
    if n % i == 0:
      divisors.append(i)
      if i != n // i: 
        divisors.append(n//i)
  return divisors


def make_primes(N):
  max = int(math.sqrt(N))
  seachList = [i for i in range(2,N+1)]
  primeNum = []
  while seachList[0] <= max:
    primeNum.append(seachList[0])
    tmp = seachList[0]
    seachList = [i for i in seachList if i % tmp != 0]
  primeNum.extend(seachList)
  return primeNum


def gcd(a, b):
    while b: a, b = b, a % b
    return a


def lcm(a, b):
    return a * b // gcd (a, b)


def count_bit(n):
  count = 0
  while n:
    n &= n-1
    count += 1
  return count


def base_10_to_n(X, n):
  if X//n: return base_10_to_n(X//n, n)+[X%n]
  return [X%n]

def base_n_to_10(X, n):
  return sum(int(str(X)[-i-1])*n**i for i in range(len(str(X))))

def base_10_to_n_without_0(X, n):
  X -= 1
  if X//n: return base_10_to_n_without_0(X//n, n)+[X%n]
  return [X%n]


def int_log(n, a):
  count = 0
  while n>=a:
    n //= a
    count += 1
  return count




from fractions import Fraction
N,A,B = IL()
data = ILL(N)

P = []
M = []
Z = []
for a,b,c in data:
  if Fraction(a,b) == Fraction(A,B):
    Z.append(c)
  elif Fraction(a,b) > Fraction(A,B):
    P.append((a*2520-b*2520*A//B,c))
  else:
    M.append((-a*2520+b*2520*A//B,c))
    
dpP = [INF for i in range(1000000)]
dpP[0] = 0
for v,c in P:
  for i in range(1000000)[::-1]:
    if i>=v:
      dpP[i] = min(dpP[i],dpP[i-v]+c)

dpM = [INF for i in range(1000000)]
dpM[0] = 0
for v,c in M:
  for i in range(1000000)[::-1]:
    if i>=v:
      dpM[i] = min(dpM[i],dpM[i-v]+c)
ans = INF
if Z:
  ans = min(Z)
for i in range(1,1000000):
  ans = min(ans,dpP[i]+dpM[i])

if ans == INF:
  print(-1)
else:
  print(ans)

Solution (Python):
n,ma,mb=map(int,input().split())
abc=[list(map(int,input().split())) for _ in range(n)]

wmax=400
inf=10**10
dp=[[[inf]*(wmax+1) for _ in range(wmax+1)] for _ in range(n+1)]
dp[0][0][0]=0

for i in range(n):
    a,b,c=abc[i]
    for j in range(wmax+1):
        for k in range(wmax+1):
            dp[i+1][j][k]=dp[i][j][k]

            if j>=a and k>=b:
                dp[i+1][j][k]=min(dp[i+1][j][k],dp[i][j-a][k-b]+c)

ans=inf

for j in range(1,wmax+1):
    for k in range(1,wmax+1):
        if dp[n][j][k]>=inf:
            continue

        if ma*k==mb*j:
            ans=min(ans,dp[n][j][k])

if ans==inf:
    print(-1)
else:
    print(ans)

Solution (Python):
import sys
from itertools import product
from collections import defaultdict

sys.setrecursionlimit(10 ** 7)
input = sys.stdin.readline
f_inf = float('inf')
mod = 10 ** 9 + 7


def resolve():
    n, Ma, Mb = map(int, input().split())
    ABC = [list(map(int, input().split())) for _ in range(n)]
    s = (n + 1) // 2
    t = n - s

    S = defaultdict(int)
    for pattern in product([0, 1], repeat=s):
        a = b = c = 0
        for idx, p in enumerate(pattern):
            if p == 1:
                a += ABC[idx][0]
                b += ABC[idx][1]
                c += ABC[idx][2]
        S[(a, b)] = min(S.get((a, b), f_inf), c)

    T = defaultdict(int)
    for pattern in product([0, 1], repeat=t):
        a = b = c = 0
        for idx, p in enumerate(pattern):
            if p == 1:
                a += ABC[s + idx][0]
                b += ABC[s + idx][1]
                c += ABC[s + idx][2]
        T[(a, b)] = min(T.get((a, b), f_inf), c)

    MAX_A = sum([a for a, _, _ in ABC])
    MAX_B = sum([b for _, b, _ in ABC])

    res = f_inf
    for k, v in S.items():
        a, b = k
        x, y = Ma, Mb
        while x <= MAX_A and y <= MAX_B:
            if T.get((x - a, y - b), -1) != -1:
                if not (a == b == 0 and x - a == x - b == 0):
                    cost = v + T[(x - a, y - b)]
                    res = min(res, cost)
            x += Ma
            y += Mb
    print(res if res != f_inf else -1)


if __name__ == '__main__':
    resolve()

Solution (Python):
N, ma, mb = map(int, input().split())
abc = [(-1, -1, -1)]
for _ in range(N):
    a, b, c = map(int, input().split())
    abc.append((a, b, c))

INF = float("inf")




dp = [[[INF for _ in range(401)] for _ in range(401)] for _ in range(N + 1)]
dp[0][0][0] = 0

for n in range(1, N + 1):
    a, b, c = abc[n]
    for i in range(401):
        for j in range(401):
            
            
            if i >= a and j >= b:
                dp[n][i][j] = min(dp[n - 1][i][j], dp[n - 1][i - a][j - b] + c)
            
            else:
                dp[n][i][j] = dp[n - 1][i][j]

ans = INF

for i in range(1, 401):
    for j in range(1, 401):
        
        if i * mb == j * ma:
            ans = min(ans, dp[N][i][j])

if ans != INF:
    print(ans)
else:
    print(-1)

Solution (Python):
N,Ma,Mb=list(map(int,input().split()))
ABC=[tuple(map(int,input().split())) for i in range(N)]
inf=float("inf")
DP=[[inf]*401 for i in range(401)]
DP[0][0]=0
for a,b,c in ABC:
   for i in reversed(range(401)):
      for j in reversed(range(401)):
         if DP[i][j]!=inf:
            DP[i+a][j+b]=min(DP[i][j]+c,DP[i+a][j+b])
ans=inf
for i in range(1,401):
   for j in range(1,401):
      if Ma*j==Mb*i:
         ans=min(ans,DP[i][j])
print(-1 if ans==inf else ans)

Solution (Python):
INF=float('inf')
N,Ma,Mb=map(int,input().split())

abc=[]
dp=[[INF]*401 for i in range(401)]
dp[0][0]=0

for i in range(N):
    a,b,c=map(int,input().split())
    for A in reversed(range(401)):
        for B in reversed(range(401)):
            if B-b>=0 and A-a>=0:
                dp[A][B]=min(dp[A][B],dp[A-a][B-b]+c)
ans=INF
for i in range(1,401):
    if i*Ma>400 or i*Mb>400:
        break
    ans=min(ans,dp[Ma*i][Mb*i])
print(ans if ans!=INF else -1)

Solution (Python):
import sys
import math
from collections import defaultdict
from collections import deque
from itertools import combinations
import bisect

sys.setrecursionlimit(1000000)
MOD = 10 ** 9 + 7
input = lambda: sys.stdin.readline().strip()
NI = lambda: int(input())
NMI = lambda: map(int, input().split())
NLI = lambda: list(NMI())
SI = lambda: input()


def main():
    N, MA, MB = NMI()
    D = []
    for _ in range(N):
        a, b, c = NMI()
        t = a*MB - b*MA
        D.append((t, c))
    D.sort()

    D1 = D[:N//2]
    D2 = D[N//2:]
    ld1 = len(D1)
    ld2 = len(D2)

    S1 = defaultdict(lambda: 10**5)
    for case in range(2**ld1):
        if case == 0: continue
        s, c = 0, 0
        for i in range(ld1):
            if (case>>i)&1:
                s += D1[i][0]
                c += D1[i][1]
        S1[s] = min(S1[s], c)

    S2 = defaultdict(lambda: 10**5)
    for case in range(2 ** ld2):
        if case == 0: continue
        s, c = 0, 0
        for i in range(ld2):
            if (case >> i) & 1:
                s += D2[i][0]
                c += D2[i][1]
        S2[s] = min(S2[s], c)

    ans = 10**5
    for s, c in list(S1.items()):
        ans = min(ans, c + S2[-s])
    ans = min(ans, S1[0], S2[0])
    if ans >= 10**5:
        print(-1)
    else:
        print(ans)



if __name__ == "__main__":
    main()

Solution (Python):
import sys
def MI(): return map(int,sys.stdin.readline().rstrip().split())


N,x,y = MI()
dp = [[[10**4]*401 for i in range(401)] for n in range(N+1)]


dp[0][0][0] = 0
for n in range(1,N+1):
    a,b,c = MI()
    for i in range(401):
        for j in range(401):
            if i >= a and j >= b:
                dp[n][i][j] = min(dp[n-1][i][j],dp[n-1][i-a][j-b]+c)
            else:
                dp[n][i][j] = dp[n-1][i][j]

z = min(dp[N][x*i][y*i] for i in range(1,min(400//x,400//y)+1))
print(-1 if z == 10**4 else z)

Solution (Python):
import sys
def MI(): return map(int,sys.stdin.readline().rstrip().split())


N,x,y = MI()
dp = [[[10**4]*401 for i in range(401)] for n in range(N+1)]


dp[0][0][0] = 0
for n in range(1,N+1):
    a,b,c = MI()
    for i in range(401):
        for j in range(401):
            if i >= a and j >= b:
                dp[n][i][j] = min(dp[n-1][i][j],dp[n-1][i-a][j-b]+c)
            else:
                dp[n][i][j] = dp[n-1][i][j]

z = min(dp[N][x*i][y*i] for i in range(1,min(400//x,400//y)+1))

if z == 10**4:
    print(-1)
else:
    print(z)

Solution (Python):
n, ma, mb = map(int, input().split())
x = [list(map(int, input().split())) for _ in range(n)]
x.insert(0, [0, 0, 0])
inf = 114514
dp = [[[inf] * (10 * n + 1) for _ in range(10 * n + 1)] for _ in range(n + 1)]
for i in range(n + 1):
    dp[i][0][0] = 0
suma, sumb = 0, 0
for i in range(1, n + 1):
    suma += x[i][0]
    sumb += x[i][1]
    for j in range(suma + 1):
        for k in range(sumb + 1):
            dp[i][j][k] = min(dp[i][j][k], dp[i - 1][j][k])
            if j >= x[i][0] and k >= x[i][1]:
                dp[i][j][k] = min(dp[i - 1][j][k], dp[i - 1][j - x[i][0]][k - x[i][1]] + x[i][2])
ans = 114514
for i in range(1, 10 * n + 1):
    for j in range(1, 10 * n + 1):
        if i * mb == j * ma:
            ans = min(ans, dp[n][i][j])
print(ans if not ans == 114514 else -1)

Solution (Python):
N,A,B = map(int,input().split())
X = [1<<20]*4040

for n in range(N):
  a,b,c = map(int,input().split())
  t = A*b-B*a
  X = [min(X[m],(0 if (m-t)%4040==0 else X[(m-t)%4040])+c) for m in range(4040)]

if 1<<18<X[0]:
  print(-1)
else:
  print(X[0])

Solution (Python):
import sys
from math import gcd
def input(): return sys.stdin.readline().strip()
sys.setrecursionlimit(10**9)

def main():
    N, Ma, Mb = map(int, input().split())
    """
    dp[i][j] = (0~iまでの薬品を使って、物質Bがjグラム余るようにするときの最小金額)
    jは整数になるとは限らないのでj=p/qと既約分数表示して(p, q)を辞書のキーとして保持する。
    """
    dp = {}
    a, b, c = map(int, input().split())
    p, q = b * Ma - a * Mb, Ma
    div = gcd(p, q)
    p, q = p // div, q // div
    dp[(p, q)] = c
    

    for i in range(1, N):
        dp2 = {}
        a, b, c = map(int, input().split())
        p, q = b * Ma - a * Mb, Ma
        div = gcd(p, q)
        p, q = p // div, q // div
        dp2[(p, q)] = c
        for p, q in dp:
            cost = dp[(p, q)]
            if (p, q) in dp2:
                dp2[(p, q)] = min(dp2[(p, q)], cost)
            else:
                dp2[(p, q)] = cost
            np, nq = p * Ma + b * q * Ma - a * q * Mb, q * Ma
            if np == 0:
                np, nq = 0, 1
            else:
                div = gcd(np, nq)
                np, nq = np // div, nq // div
            if (np, nq) in dp2:
                dp2[(np, nq)] = min(dp2[(np, nq)], cost + c)
            else:
                dp2[(np, nq)] = cost + c
        dp = dp2
        
    if (0, 1) in dp:
        print(dp[(0, 1)])
    else:
        print(-1)



if __name__ == "__main__":
    main()

Solution (Python):
from sys import stdin
def input():
    return stdin.readline().strip()

n, ma, mb = map(int, input().split())
a, b, c = [], [], []
for _ in range(n):
    i, j, k = map(int, input().split())
    a.append(i)
    b.append(j)
    c.append(k)

sum_a = sum(a) + 1
sum_b = sum(b) + 1


dp = [[float('inf')] * sum_b for _ in range(sum_a)]
dp[0][0] = 0

from copy import deepcopy
for i in range(n):
    new_dp = deepcopy(dp)
    ai, bi, ci = a[i], b[i], c[i]
    for x in range(sum_a - ai):
        for y in range(sum_b - bi):
            new_dp[x+ai][y+bi] = dp[x][y] + ci
    for x in range(sum_a):
        for y in range(sum_b):
            if dp[x][y] > new_dp[x][y]:
                dp[x][y] = new_dp[x][y]

ans = float('inf')
for x in range(1, sum_a):
    for y in range(1, sum_b):
        if x * mb == y * ma and dp[x][y] < ans:
            ans = dp[x][y]

if ans == float('inf'):
    print(-1)
else:
    print(ans)

Solution (Python):
import sys
readlines = sys.stdin.buffer.readlines
input = sys.stdin.buffer.readline
N, Ma, Mb = map(int, input().split())
X = [map(int, line.split()) for line in readlines()]
X = [(a*Mb-b*Ma, c) for a, b, c in X]

INF = 1 << 30
MAX = 10000
MID = MAX//2
dp = [INF]*(MAX+1)
ans = INF
for i, (x, c) in enumerate(X):
    if x == 0:
        ans = min(ans, c)
        continue

    if x > 0:
        for j in range(MAX, x-1, -1):
            dp[j] = min(dp[j], dp[j-x]+c)
    else:
        for j in range(MAX+x):
            dp[j] = min(dp[j], dp[j-x]+c)

    dp[MID+x] = min(dp[MID+x], c)

ans = min(ans, dp[MID])
print(ans if ans < INF else -1)

Solution (Python):
import sys
readlines = sys.stdin.buffer.readlines
input = sys.stdin.buffer.readline
N, Ma, Mb = map(int, input().split())
X = [tuple(map(int, line.split())) for line in readlines()]

INF = 1 << 30
x = [[INF]*201 for _ in [0]*201]
y = [[INF]*201 for _ in [0]*201]

n = N//2
X, Y = X[:n], X[n:]
for bit in range(1 << n):
    totA = totB = cost = 0
    for i in range(n):
        if bit >> i & 1:
            a, b, c = X[i]
            totA += a
            totB += b
            cost += c

    x[totA][totB] = min(x[totA][totB], cost)

for bit in range(1 << (N-n)):
    totA = totB = cost = 0
    for i in range(N-n):
        if bit >> i & 1:
            a, b, c = Y[i]
            totA += a
            totB += b
            cost += c

    y[totA][totB] = min(y[totA][totB], cost)

ans = INF
M = 405//max(Ma, Mb)
for i, t in enumerate(x):
    for j, s in enumerate(t):
        if s == INF:
            continue
        for k in range(1, M+1):
            I = k*Ma-i
            J = k*Mb-j
            if 0 <= I <= 200 and 0 <= J <= 200:
                ans = min(ans, s + y[I][J])

print(ans if ans < INF else -1)

Solution (Python):
import collections
import copy
INF = 10000


N, Ma, Mb = map(int, input().split())
medichine = [tuple(map(int, input().split())) for _ in range(N)]

dp = {}

dp = collections.defaultdict(lambda:INF)
dp[0,0] = 0

for a, b, c in medichine:
    dp_ = copy.copy(dp)
    for ca,cb in dp.keys():
        dp_[ca+a, cb+b] = min(dp_[ca+a, cb+b], dp[ca,cb]+c)
    dp = dp_    

ans = INF
for ca,cb in dp.keys():
    if ca == cb == 0: continue
    if ca*Mb == cb*Ma:
        ans = min(ans, dp[ca,cb])
        
print(-1 if ans == INF else ans)

Solution (Python):
import sys
input = sys.stdin.buffer.readline




def RD(): return input().rstrip().decode()
def II(): return int(input())
def FI(): return int(input())
def MI(): return map(int,input().split())
def MF(): return map(float,input().split())
def LI(): return list(map(int,input().split()))
def LF(): return list(map(float,input().split()))
def TI(): return tuple(map(int,input().split()))



def main():
	n,ma,mb=MI()
	dp=[[10**6]*(n*10+15) for i in range(n*10+15)]
	for i in range(n+1):
		dp[0][0]=0

	for _ in range(n):
		a,b,c=MI()
		for aa in range(n*10+1,-1,-1):
			for bb in range(n*10+1,-1,-1):
				dp[a+aa][b+bb]=min(dp[aa][bb]+c,dp[a+aa][b+bb])

	ans=10**6

	for i in range(1,1000):
		try:
			ans=min(ans,dp[ma*i][mb*i])
		except:
			break

	print(ans if ans<10**6 else -1)





























if __name__ == "__main__":
	main()