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):
def main(sample_file = ''):

    """ convenient functions
    
    
    
    
    
    """

    """convenient decorator
    
    
        
        
        
        
        
        
        
        
        
        
    """
    
    
    import sys
    sys.setrecursionlimit(10**7)
    from itertools import accumulate, combinations, permutations, product 
    
    from math import factorial, ceil, floor, sqrt
    def factorize(n):
        """return the factors of the Arg and count of each factor
        
        Args:
            n (long): number to be resolved into factors
        
        Returns:
            list of tuples: factorize(220) returns [(2, 2), (5, 1), (11, 1)]
        """
        fct = []  
        b, e = 2, 0  
        while b * b <= n:
            while n % b == 0:
                n = n // b
                e = e + 1
            if e > 0:
                fct.append((b, e))
            b, e = b + 1, 0
        if n > 1:
            fct.append((n, 1))
        return fct
    def combinations_count(n, r):
        """Return the number of selecting r pieces of items from n kinds of items.
        
        Args:
            n (long): number
            r (long): number
        
        Raises:
            Exception: not defined when n or r is negative
        
        Returns:
            long: number
        """
        
        if n < 0 or r < 0:
            raise Exception('combinations_count(n, r) not defined when n or r is negative')
        if n - r < r: r = n - r
        if r < 0: return 0
        if r == 0: return 1
        if r == 1: return n
        numerator = [n - r + k + 1 for k in range(r)]
        denominator = [k + 1 for k in range(r)]
        for p in range(2,r+1):
            pivot = denominator[p - 1]
            if pivot > 1:
                offset = (n - r) % p
                for k in range(p-1,r,p):
                    numerator[k - offset] /= pivot
                    denominator[k] /= pivot
        result = 1
        for k in range(r):
            if numerator[k] > 1:
                result *= int(numerator[k])
        return result
    def combinations_with_replacement_count(n, r):
        """Return the number of selecting r pieces of items from n kinds of items allowing individual elements to be repeated more than once.
        
        Args:
            n (long): number
            r (long): number
        
        Raises:
            Exception: not defined when n or r is negative
        
        Returns:
            long: number
        """
        if n < 0 or r < 0:
            raise Exception('combinations_with_replacement_count(n, r) not defined when n or r is negative')
        elif n == 0:
            return 1
        else:
            return combinations_count(n + r - 1, r)
    from bisect import bisect_left, bisect_right
    from collections import deque, Counter, defaultdict 
    from heapq import heapify, heappop, heappush, heappushpop, heapreplace,nlargest,nsmallest 
    from copy import deepcopy, copy 
    import operator
    from operator import itemgetter 
    
    
    from functools import reduce, lru_cache
    def chmin(x, y):
        """change minimum
        if x > y, x = y and return (x, True).
        convenient when solving problems of dp[i]
        
        Args:
            x (long): current minimum value
            y (long): potential minimum value
        
        Returns:
            (x, bool): (x, True) when updated, else (x, False)
        """
        if x > y:
            x = y
            return (x, True)
        else:
            return (x, False)
    def chmax(x, y):
        """change maximum
        if x < y, x = y and return (x, True).
        convenient when solving problems of dp[i]
        
        Args:
            x (long): current maximum value
            y (long): potential maximum value
        
        Returns:
            (x, bool): (x, True) when updated, else (x, False)
        """
        if x < y:
            x = y
            return (x, True)
        else:
            return (x, False)

    from fractions import gcd 
    def gcds(numbers):
        return reduce(gcd, numbers)
    def lcm(x, y):
        return (x * y) // gcd(x, y)
    def lcms(numbers):
        return reduce(lcm, numbers, 1)
    def make_divisors(n, reversed=False):
        """create list of divisors
        
        Args:
            number (int): number from which list of divisors is created
            reversed (bool, optional): ascending order if False. Defaults to False.
        
        Returns:
            list: list of divisors
        """
        divisors = set()
        for i in range(1, int(n**0.5)+1):
            if n % i == 0:
                divisors.add(i)
                divisors.add(n//i)
        return sorted(list(divisors),reverse=reversed)
    
    
    
    INF = 10 ** 18
    MOD = 10 ** 9 + 7
    modpow = lambda a, n, p = MOD: pow(a, n, p) 
    def modinv(a, p = MOD):
        
        
        return modpow(a, p-2, p)
    def modinv_list(n, p = MOD):
        if n <= 1:
            return [0,1][:n+1]
        else:
            inv_t = [0,1]
            for i in range(2, n+1):
                inv_t += [inv_t[p % i] * (p - int(p / i)) % p]
            return inv_t
    def modfactorial_list(n, p = MOD):
        if n == 0:
            return [1]
        else:
            l = [0] * (n+1)
            tmp = 1
            for i in range(1, n+1):
                tmp = tmp * i % p
                l[i] = tmp
            return l
    def modcomb(n, k, fac_list = [], p = MOD):
        
        
        from math import factorial
        if n < 0 or k < 0 or n < k: return 0
        if n == 0 or k == 0: return 1
        if len(fac_list) <= n:
            a = factorial(n) % p
            b = factorial(k) % p
            c = factorial(n-k) % p
        else:
            a = fac_list[n]
            b = fac_list[k]
            c = fac_list[n-k]
        return (a * modpow(b, p-2, p) * modpow(c, p-2, p)) % p
    def modadd(a, b, p = MOD):
        return (a + b) % MOD
    def modsub(a, b, p = MOD):
        return (a - b) % p
    def modmul(a, b, p = MOD):
        return ((a % p) * (b % p)) % p
    def moddiv(a, b, p = MOD):
        return modmul(a, modpow(b, p-2, p))

    class UnionFindTree:
        """union find tree class
        TODO: fix this description...
        how to use (example):
        >>  uf = UnionFindTree(N) 
        >>  if uf.find_root(a) == uf.find_root(b):
        >>      do something
        >>  else:
        >>      do something
        >>      uf.unite(a, b)
        """
        def __init__(self, N):
            self.root = [-1] * (N+1)
            self.rank   = [0]  * (N+1)
            self.connected_num = [1] * (N+1)
    
        def find_root(self,x):
            root = self.root
            while root[x] != -1:
                x = root[x]
            return x
    
        def unite(self,x,y):
            root = self.root
            rank = self.rank
            connected_num = self.connected_num
            find_root = self.find_root
    
            rx = find_root(x)
            ry = find_root(y)
            if rx != ry:
                if rank[rx] < rank[ry]:
                    root[rx] = ry
                    rx,ry = ry,rx
                else:
                    if rank[rx] == rank[ry]:
                        rank[rx] += 1
                    root[ry] = rx       
                connected_num[rx] += connected_num[ry]

    
    
    
    
    

    def BellmanFord(N, M, ABC, vertex_start, vertex_end, value_if_inf = -1, find_shortest = False):
        """to calculate furthest or shortest length between vertex_start and vertex_end using BellmanFord algorithm
        
        Args:
            N (int): number of vertices
            M (int): number of edges
            ABC (list): [(ai, bi, ci) for _ in range(N)] where i-th edge is directed from vertex ai to vertex bi and the length is ci 
            vertex_start (int): start vertex. usually use 0.
            vertex_end (int): end vertex. usually use N-1.
            value_if_inf (int or string as you like, optional): value you want when the furthest (or shortest) distance is infinite (or -infinite). Defaults to -1.
            find_shortest (bool, optional): choose False to find furthest path. Defaults to False.
        
        Returns:
            int or string: normally int (but can be str if you set value_if_inf to str)
            
        Example:
                N, M, P = R()
                ABC = [R() for _ in range(M)]
                ABC = [(a-1, b-1, c-P) for a, b, c in ABC]
                print(BellmanFord(N, M, ABC, 0, N-1, value_if_inf = 'inf'))

        """

        def make_reachable_list(N, M, ABC, vertex_start, vertex_end):
            reachable_to_direct = defaultdict(list)
            reachable_from_direct = defaultdict(list)
            reachable_from_start = [False] * N
            reachable_to_end = [False] * N
            reachable_from_start[vertex_start] = True
            reachable_to_end[vertex_end] = True
            reachable_from_both_sides = [False] * N
            dfs_from_start = []
            dfs_to_end = []
            for a, b, c in ABC:
                reachable_to_direct[a].append(b)
                reachable_from_direct[b].append(a)
                if a == vertex_start:
                    dfs_from_start.append(b)
                    reachable_from_start[b] = True
                if b == vertex_end:
                    dfs_to_end.append(a)
                    reachable_to_end[a] = True
            while dfs_from_start:
                v = dfs_from_start.pop()
                for i in reachable_to_direct[v]:
                    if not reachable_from_start[i]:
                        reachable_from_start[i] = True
                        dfs_from_start.append(i)
            while dfs_to_end:
                v = dfs_to_end.pop()
                for i in reachable_from_direct[v]:
                    if not reachable_to_end[i]:
                        reachable_to_end[i] = True
                        dfs_to_end.append(i)
            for i in range(N):
                reachable_from_both_sides[i] = reachable_from_start[i] and reachable_to_end[i]
            return reachable_from_both_sides
        
        reachable_from_both_sides = make_reachable_list(N, M, ABC, vertex_start, vertex_end)
        
        if find_shortest:
            dist = [INF for i in range(N)]
        else:
            dist = [-INF for i in range(N)]
        
        dist[vertex_start] = 0
        for i in range(N):
            updated = False
            for a, b, c in ABC:
                if not reachable_from_both_sides[a]:
                    continue
                elif find_shortest:
                    update_condition = dist[a] + c < dist[b]
                else:
                    update_condition = dist[a] + c > dist[b]
                if dist[a] != INF and update_condition:
                    dist[b] = dist[a] + c
                    updated = True
                    if i == N-1:
                        return value_if_inf
            if not updated:
                break
        return dist[vertex_end]

    """ initialize variables and set inputs
    
        
        
            
            
    
        
        
        
        
        
        
        
    
        
        
        
        
    
        
        
    """

    
    r = lambda: sys.stdin.readline().strip()
    r_int = lambda: int(r())
    r_float = lambda: float(r())
    R = lambda: list(map(int, r().split()))
    R_map = lambda: map(int, r().split())
    R_float = lambda: list(map(float, r().split()))
    R_tuple = lambda: tuple(map(int, r().split()))

    """ how to treat input
    
    
    
    
    
    
    
    """

    
    if sample_file:
        sys.stdin = open(sample_file)
        
    
    

    N, MA, MB = R()
    ABC = [R() for _ in range(N)]
    dp = [[INF]*(420) for _ in range(420)]
    dp[0][0] = 0

    for a, b, c in ABC:
        
        for i in range(400, -1, -1):
            for j in range(400, -1, -1):
                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])
    else:
        if ans == INF:
            ans = -1
    print(ans)
    
    
    

    """memo: how to use defaultdict of list
    
    Dic = defaultdict(list)
    
    Dic[x].append(y)
    
    for k, v in Dic.items():
    """
    
    """memo: how to solve binary problems
    
    >>> a = 5
    >>> bin_str_a = format(a, '
    >>> print(bin_str_a)
    0b0101 
    """
    
    """memo: how to solve the problem
    creating simple test/answer
    greed
    simple dp
    graph
    """

if __name__ == '__main__':
    main()

Solution (Python):
inf = 10 ** 18

a = []
b = []
c = []
n, ma, mb = map(int, input().split())

for _ in range(n):
    a_, b_, c_ = map(int, input().split())
    a.append(a_)
    b.append(b_)
    c.append(c_)

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

for i in range(n):
    for j in range(p + 1):
        for k in range(p + 1):
            if dp[i][j][k] == inf:
                continue
            dp[i + 1][j][k] = min(dp[i+1][j][k], dp[i][j][k])
            dp[i + 1][j + a[i]][k + b[i]
                                ] = min(dp[i + 1][j + a[i]][k + b[i]], dp[i][j][k] + c[i])

ans = inf
for j in range(p)[1::]:
    for k in range(p)[1::]:
        if j * mb == k * ma:
            ans = min(ans, dp[n][j][k])

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

Solution (Python):
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
import math
import bisect
import random
from itertools import permutations, accumulate, combinations, product
import sys
from pprint import pprint
from copy import deepcopy
import string
from bisect import bisect_left, bisect_right
from math import factorial, ceil, floor
from operator import mul
from functools import reduce
from pprint import pprint


sys.setrecursionlimit(2147483647)
INF = 10 ** 20
def LI(): return list(map(int, sys.stdin.buffer.readline().split()))
def I(): return int(sys.stdin.buffer.readline())
def LS(): return sys.stdin.buffer.readline().rstrip().decode('utf-8').split()
def S(): return sys.stdin.buffer.readline().rstrip().decode('utf-8')
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): return [S() for i in range(n)]
def LSR(n): return [LS() for i in range(n)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]
mod = 1000000007


def gcd(i, j):
    while j:
        i, j = j, i % j
    return i


n, a_ratio, b_ratio = LI()
solution = LIR(n)
dp = {(0, 0): 0}
for a, b, c in solution:
    for (ai, bi), ci in list(dp.items()):
        
        
        
        dp[(ai + a, bi + b)] = min(dp.get((ai + a, bi + b), INF), ci + c)


ans = INF
for i in range(1, max(400 // a_ratio, 400 // b_ratio)):
    ans = min(ans, dp.get((a_ratio * i, b_ratio * i), INF))

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

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

DP = []
for _ in range(N+1):
    temp = [[-1]*(N*10+1) for _ in range(N*10+1)]
    DP.append(temp)
DP[0][0][0] = 0

for i in range(1,N+1):
    A,B,C = Data[i-1]
    for a in range(0,N*10+1):
        for b in range(0,N*10+1):
            if DP[i-1][a][b] != -1:
                
                if DP[i][a][b] == -1:
                    DP[i][a][b] = DP[i-1][a][b]
                else:
                    DP[i][a][b] = min(DP[i][a][b],DP[i-1][a][b])

                
                if DP[i][a+A][b+B] == -1:
                    DP[i][a+A][b+B] = DP[i-1][a][b]+C
                else:
                    DP[i][a+A][b+B] = min(DP[i][a+A][b+B],DP[i-1][a][b]+C)
ans = -1
for a in range(1,N*10+1):
    for b in range(1,N*10+1):
        if DP[N][a][b] != -1 and a * Mb == b * Ma:
            if ans == -1:
                ans = DP[N][a][b]
            else:
                ans = min(ans,DP[N][a][b])
print(ans)

Solution (Python):
import sys

INF = float('inf')

n, ma, mb = map(int, sys.stdin.readline().split())
abc = map(int, sys.stdin.read().split())
abc = list(zip(*[abc] * 3))

def main():
    sa = 0
    sb = 0
    for i in range(n):
        sa += abc[i][0]
        sb += abc[i][1]

    res = [[INF] * (sb + 1) for _ in range(sa + 1)]
    res[0][0] = 0

    for a, b, c in abc:

        for j in range(sa, -1, -1):
            for k in range(sb, -1, -1):
                if j >= a and k >= b:
                    res[j][k] = min(res[j][k], res[j-a][k-b] + c)

    ans = INF
    for i in range(1, min(sa//ma, sb//mb) + 1):
        ans = min(ans, res[ma*i][mb*i])

    if ans == INF:
        return -1
    else:
        return ans

if __name__ == '__main__':
    ans = main()
    print(ans)

Solution (Python):
import sys
import numpy as np

I = np.array(sys.stdin.read().split(), dtype=np.int64)
n, ma, mb = I[:3]
abc = I[3:].reshape(n, 3)

def main():
    sa, sb = np.sum(abc, axis=0)[:2]
    res = np.full((sa+1, sb+1), np.inf)
    res[0, 0] = 0

    for a, b, c in abc:
        res[a:, b:] = np.minimum(res[a:, b:], res[:-a, :-b] + c)
    
    a = np.arange(ma, sa+1, ma)
    b = np.arange(mb, sb+1, mb)
    lim = min(sa//ma, sb//mb)
    ans = np.amin(res[a[:lim], b[:lim]])
    
    if ans == np.inf:
        return -1
    return int(ans)

if __name__ == '__main__':
    ans = main()
    print(ans)

Solution (Python):
import sys
import numpy as np

I = np.array(sys.stdin.read().split(), dtype=np.int64)
n, ma, mb = I[:3]
abc = I[3:].reshape(n, 3)

def main():
    sa, sb = np.sum(abc, axis=0)[:2]
    res = np.full((sa+1, sb+1), np.inf)
    res[0, 0] = 0

    for a, b, c in abc:
        res[a:, b:] = np.minimum(res[a:, b:], res[:-a, :-b] + c)
    
    ans = np.inf
    for i in range(1, min(sa//ma, sb//mb) + 1):
        ans = np.minimum(ans, res[ma * i, mb * i])
    
    if ans == np.inf:
        return -1
    return int(ans)
    
if __name__ == '__main__':
    ans = main()
    print(ans)

Solution (Python):
import sys

INF = float('inf')

n, ma, mb = map(int, sys.stdin.readline().split())
a, b, c = [], [], []
for _ in range(n):
    ai, bi, ci = map(int, sys.stdin.readline().split())
    a.append(ai); b.append(bi); c.append(ci)

def main():
    sa = sum(a)
    sb = sum(b)
    res = [[[INF] * (sb + 1) for _ in range(sa + 1)] for _ in range(n + 1)]
    res[0][0][0] = 0
    for i in range(n):
        for j in range(sa + 1):
            for k in range(sb + 1):
                if j >= a[i] and k >= b[i]:
                    res[i+1][j][k] = min(res[i][j-a[i]][k-b[i]] + c[i], res[i][j][k])
                else:
                    res[i+1][j][k] = res[i][j][k]
    ans = INF
    for i in range(1, min(sa//ma, sb//mb)+1):
        ans = min(ans, res[n][ma * i][mb * i])
    
    if ans == INF:
        return -1
    else:
        return ans

if __name__ == '__main__':
    ans = main()
    print(ans)

Solution (Python):
N,Ma,Mb=map(int,input().split())
INF=40*100+1
dp=[[INF for i in range(10*N+1)] for j in range(10*N+1)]
dp[0][0]=0
ans=INF
for p in range(N):
  a,b,c=map(int,input().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:
        dp[i+a][j+b]=min(dp[i+a][j+b],dp[i][j]+c)
        if (i+a)/(j+b)==Ma/Mb:
          ans=min(ans,dp[i+a][j+b])
          
if ans==INF:
  print(-1)
else:
  print(ans)

Solution (Python):
N, A, B = map(int, input().split())
X = [1<<20] * 4040
for _ in range(N):
    a, b, c = map(int, input().split())
    t = A*b-B*a
    X = [min(X[i], (0 if (i-t)%4040 == 0 else X[(i-t)%4040]) + c) for i in range(4040)]
print(-1 if X[0] > 1<<18 else X[0])

Solution (Python):
N, A, B = map(int, input().split())
X = [1<<20] * 8080
for _ in range(N):
    a, b, c = map(int, input().split())
    t = A*b-B*a
    X = [min(X[i], (0 if (i-t)%8080 == 0 else X[(i-t)%8080]) + c) for i in range(8080)]
print(-1 if X[0] > 1<<18 else X[0])

Solution (Python):
if __name__ == '__main__':
    N,M_a,M_b=list(map(int,input().split()))
    A,B,C=[],[],[]
    for i in range(N):
        a,b,c=list(map(int,input().split()))
        A.append(a)
        B.append(b)
        C.append(c)

    dp=[[[1e10 for i in range(sum(B)+max(B)+1)] for j in range(sum(A)+max(A)+1)] for k in range(N+1)]
    dp[0][0][0]=0

    for i in range(N):
        for c_a in range(sum(A)+1):
            for c_b in range(sum(B)+1):
                if dp[i][c_a][c_b]==1e10:
                    continue
                dp[i+1][c_a][c_b]=min(dp[i+1][c_a][c_b],dp[i][c_a][c_b])
                dp[i+1][c_a+A[i]][c_b+B[i]]=min(dp[i+1][c_a+A[i]][c_b+B[i]],dp[i][c_a][c_b]+C[i])
    ans_list=[1e10]
    for c_a in range(1,sum(A)+1):
        for c_b in range(1,sum(B)+1):
            if c_a*M_b==c_b*M_a:
                ans_list.append(dp[N][c_a][c_b])
    ans=min(ans_list)
    if  ans==1e10:
        print(-1)
    else:
        print(ans)

Solution (Python):


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

a = [0] * N
b = [0] * N
c = [0] * N
for i in range(N):
    a[i], b[i], c[i] = map(int, input().split())
    

INF = float("inf")
sA = sum(a)
sB = sum(b)

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

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


ans = INF

x = Ma
y = Mb
while x <= sA and y <= sB :

    ans = min(ans, dp[N][x][y])
    x += Ma
    y += Mb


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

Solution (Python):
import copy

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

INF, W = 10000, 10 * max(Ma, Mb) * N
dp = [[INF] * (2 * W + 1)]

for a, b, c in ABC:
    dp.append(copy.deepcopy(dp[-1]))
    df = a * Mb - b * Ma
    dp[-1][df] = min(dp[-1][df], c)
    for d in range(-W, W + 1):
        dp[-1][df + d] = min(dp[-1][df + d], c + dp[-2][d])

print("-1" if dp[N][0] == INF else dp[N][0])

Solution (Python):
import copy

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

INF, W = 10 ** 10, 10 * 10 * N
dp = [[INF] * (2 * W + 1)]

for a, b, c in ABC:
    dp.append(copy.deepcopy(dp[-1]))
    df = a * Mb - b * Ma
    dp[-1][df] = min(c, dp[-1][df])
    for d in range(-W, W + 1):
        dp[-1][df + d] = min(c + dp[-2][d], dp[-1][df + d])

print("-1" if dp[N][0] == INF else dp[N][0])

Solution (Python):
n,ma,mb=map(int,input().split())
abc = [list(map(int,input().split())) for _ in range(n)]
suma = sum([abc[i][0] for i in range(n)])+1
sumb = sum([abc[i][1] for i in range(n)])+1
dp = [[[5000 for j in range(sumb)]for i in range(suma)]for k in range(n+1)]
for i in range(n+1):
    dp[i][0][0] = 0
for k in range(n):
    for i in range(suma):
        for j in range(sumb):
            if i>=abc[k][0] and j>=abc[k][1]:
                dp[k+1][i][j] = min(dp[k][i][j],dp[k][i-abc[k][0]][j-abc[k][1]]+abc[k][2])
            else:
                dp[k+1][i][j]=dp[k][i][j]

flag = 0
res = 5000
for i in range(1,500):
    if ma*i >=suma or mb*i >= sumb:
        break
    res = min(res,dp[n][ma*i][mb*i])
    flag = 1
if res != 5000:
    print(res)
else:
    print("-1")

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

m = n * 10 + 1

dp = [[[float('inf')] * m for j in range(m)] for i in range(n + 1)]
for i in range(n + 1):
    dp[i][0][0] = 0

for i in range(n):
    for j in range(m):
        for k in range(m):
            dp[i+1][j][k] = min(dp[i+1][j][k], dp[i][j][k])

            
            jj = j + abc[i][0]
            kk = k + abc[i][1]
            if jj < m and kk < m:
                dp[i+1][jj][kk] = min(dp[i+1][jj][kk], dp[i][j][k] + abc[i][2])

from fractions import gcd
ans = float('inf')
for i in range(1, m):
    for j in range(1, m):
        g = gcd(i, j)
        if i // g == ma and j // g == mb:
            ans = min(ans, dp[-1][i][j])

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

Solution (Python):
n, ma, mb = [int(i) for i in input().split()]
lst = [[int(i) for i in input().split()] for _ in range(n)]
lst.sort(key=lambda x: x[2])
dic = {}
def push(k,v):
    if k in dic:
        dic[k] = min(dic[k],v)
    else:
        dic[k] = v


for i in lst:
    k, v = i[0] * mb - i[1] * ma, i[2]
    l = [[j, dic[j]] for j in dic]
    for item in l:
        push(item[0] + k, item[1] + v)
    push(k, v)

print(dic[0] if 0 in dic else '-1')

Solution (Python):
inf=10**10
n,ma,mb=map(int,input().split())
abc=[list(map(int,input().split())) for _ in range(n)]
memo=[[inf]*401 for _ in range(401)]
memo[0][0]=0
for a,b,c in abc:
  for i in range(400,-1,-1):
    for j in range(400,-1,-1):
      if memo[i][j]!= inf :
        memo[i+a][j+b]= min(memo[i+a][j+b], memo[i][j] + c)


ans=inf
for i in range(1,min(400//ma,400//mb)):
  ans=min(ans, memo[ma*i][mb*i])

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

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

INF = 4001
Na = sum(A)
Nb = sum(B)
dp = [[[INF]*(Nb+1) for _ in range(Na+1)] for _ in range(N+1)]
dp[0][0][0] = 0

for i in range(N):
    for j in range(Na+1):
        for k in range(Nb+1):
            if j < A[i] or k < B[i]:
                dp[i+1][j][k] = dp[i][j][k]
            else:
                dp[i+1][j][k] = min(dp[i][j][k], dp[i][j-A[i]][k-B[i]]+C[i])
            
ans = INF
for i in range(1, N+1):
    for j in range(1, Na+1):
        for k in range(1, Nb+1):
            if j*Mb == k*Ma:
                ans = min(ans, dp[i][j][k])
                
if ans == INF:
    ans = -1
    
print(ans)

Solution (Python):
import sys
sys.setrecursionlimit(2147483647)
INF=float("inf")
MOD=10**9+7
input=lambda :sys.stdin.readline().rstrip()
from itertools import product
from copy import deepcopy
def resolve():
    n,ma,mb=map(int,input().split())
    ABC=[tuple(map(int,input().split())) for _ in range(n)]
    M=400

    dp=[[INF]*(M+1) for _ in range(M+1)]
    dp[0][0]=0

    for a,b,c in ABC:
        for x,y in product(range(M,-1,-1),repeat=2):
            if(x+a<=M and y+b<=M):
                dp[x+a][y+b]=min(dp[x+a][y+b],dp[x][y]+c)

    ans=INF
    for x,y in product(range(1,M+1),repeat=2):
        if(x*mb==y*ma): ans=min(ans,dp[x][y])
    if(ans==INF): ans=-1
    print(ans)
resolve()

Solution (Python):
import sys
sys.setrecursionlimit(2147483647)
INF=float("inf")
MOD=10**9+7
input=lambda :sys.stdin.readline().rstrip()
from itertools import product
from copy import deepcopy
def resolve():
    n,ma,mb=map(int,input().split())
    ABC=[tuple(map(int,input().split())) for _ in range(n)]
    M=400

    dp=[[INF]*(M+1) for _ in range(M+1)]
    dp[0][0]=0

    for a,b,c in ABC:
        ndp=deepcopy(dp)
        for x,y in product(range(M+1),repeat=2):
            if(x+a<=M and y+b<=M):
                ndp[x+a][y+b]=min(ndp[x+a][y+b],dp[x][y]+c)
        dp=ndp

    ans=INF
    for x,y in product(range(1,M+1),repeat=2):
        if(x*mb==y*ma): ans=min(ans,dp[x][y])
    if(ans==INF): ans=-1
    print(ans)
resolve()

Solution (Python):
import sys
sys.setrecursionlimit(2147483647)
INF=float("inf")
MOD=10**9+7
input=lambda :sys.stdin.readline().rstrip()
from itertools import product
def resolve():
    n,ma,mb=map(int,input().split())
    ABC=[tuple(map(int,input().split())) for _ in range(n)]
    M=400

    dp=[[INF]*(M+1) for _ in range(M+1)]
    dp[0][0]=0

    for a,b,c in ABC:
        ndp=[a[:] for a in dp]
        for x,y in product(range(M+1),repeat=2):
            if(x+a<=M and y+b<=M):
                ndp[x+a][y+b]=min(ndp[x+a][y+b],dp[x][y]+c)
        dp=ndp

    ans=INF
    for x,y in product(range(1,M+1),repeat=2):
        if(x*mb==y*ma): ans=min(ans,dp[x][y])
    if(ans==INF): ans=-1
    print(ans)
resolve()

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

INF = 10**8
MAX_M = 400
dp = [[[INF] * (MAX_M + 1) for _ in range(MAX_M + 1)] for _ in range(2)]
dp[0][0][0] = 0
for i, (a, b, c) in enumerate(med):
    i0 = (i + 0) % 2
    i1 = (i + 1) % 2
    for x in range(MAX_M + 1):
        for y in range(MAX_M + 1):
            if x - a >= 0 and y - b >= 0:
                dp[i1][x][y] = min(dp[i0][x][y], dp[i0][x - a][y - b] + c)
            else:
                dp[i1][x][y] = dp[i0][x][y]

ans = INF
for i in range(1, MAX_M + 1):
    if ma * i > MAX_M or mb * i > MAX_M:
        break
    ans = min(ans, dp[n % 2][ma * i][mb * i])
if ans == INF:
    ans = -1

print(ans)

Solution (Python):
def main():
    N, Ma, Mb = map(int, input().split())
    a = [0] * N
    b = [0] * N
    c = [0] * N
    for i in range(N):
        a[i], b[i], c[i] = map(int, input().split())

    dp = [[[float('inf')] * (405) for _ in range(405)] for _ in range(N + 5)]    
    dp[0][0][0] = 0

    for i in range(N):
        for j in range(401):
            for k in range(401):
                if dp[i][j][k] == float('inf'):
                    continue
                dp[i+1][j][k] = min(dp[i+1][j][k], dp[i][j][k])
                dp[i+1][j+a[i]][k+b[i]] = min(dp[i+1][j+a[i]][k+b[i]], dp[i][j][k] + c[i])

    ans = float('inf')
    for i in range(1,401):
        for j in range(1,401):
            if Ma * j == Mb * i:
                ans = min(ans, dp[N][i][j])

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


if __name__ == "__main__":
    main()