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):
import sys




def read_int_list():
    return list(map(int, input().split()))


def read_str_list():
    return input().split()


def read_int():
    return int(input())


def read_str():
    return input()


def solve():
    M = 10
    n, ma, mb = read_int_list()
    p = [read_int_list() for i in range(n)]
    min_c = {(0, 0, 0): 0}

    for i in range(1, n + 1):
        a, b, c = p[i - 1]
        for u in range(0, M * (i - 1) + 1):
            for v in range(0, M * (i - 1) + 1):
                if (i - 1, u, v) in min_c:
                    cost = min_c[(i - 1, u, v)]
                    cc = cost + c
                    uu = u + a
                    vv = v + b
                    if (i, uu, vv) not in min_c:
                        min_c[(i, uu, vv)] = cc
                    if cc < min_c[(i, uu, vv)]:
                        min_c[(i, uu, vv)] = cc
                        
                    cc = cost
                    uu = u
                    vv = v
                    if (i, uu, vv) not in min_c:
                        min_c[(i, uu, vv)] = cc
                    if cc < min_c[(i, uu, vv)]:
                        min_c[(i, uu, vv)] = cc

    inf = 10 ** 20
    res = inf
    for u in range(0, M * n + 1):
        for v in range(0, M * n + 1):
            if u == 0 and v == 0:
                continue
            if u * mb == v * ma:
                if (n, u, v) in min_c:
                    cost = min_c[(n, u, v)]
                    if cost < res:
                        res = cost
    if res == inf:
        res = -1
    return res


def main():
    res = solve()
    print(res)


main()

Solution (Python):
N, M_a, M_b = map(int, raw_input().split())
v = [map(int, raw_input().split()) for i in range(N)]
def solve():
    dp = {(0, 0): 0}
    for i in range(N):
        a, b, c = v[i]
        for (A, B), C in dp.items():
            nA, nB, nC = A+a, B+b, C+c
            if not (nA, nB) in dp:
                dp[nA, nB] = nC
            else:
                dp[nA, nB] = min(dp[nA, nB], nC)
    for (a, b), c in sorted(dp.items(), key=lambda x: x[1]):
        if (a, b) == (0, 0):
            continue
        if a*M_b == b*M_a:
            return c
    return -1
print solve()

Solution (Python):

n,ma,mb = map(int, input().split())
a = []
b = []
c = []
for i in range(n):
    ai,bi,ci = map(int, input().split())
    a.append(ai)
    b.append(bi)
    c.append(ci)
    
max_sum = n * 10
max_cost = 100000000
dp = [[[max_cost for k in range(max_sum+1)] for j in range(max_sum+1)] for i in range(n+1)]

dp[0][0][0] = 0
for i in range(n):
    for ca in range(max_sum+1):
        for cb in range(max_sum+1):
            if(dp[i][ca][cb] == max_cost):
                continue
            dp[i+1][ca][cb] = min(dp[i+1][ca][cb], dp[i][ca][cb])
            dp[i+1][ca+a[i]][cb+b[i]] = min(dp[i+1][ca+a[i]][cb+b[i]], dp[i][ca][cb]+c[i])

ans = max_cost
for ca in range(1,max_sum+1):
    for cb in range(1,max_sum+1):
        if(ca*mb == cb*ma):
            ans = min(ans, dp[n][ca][cb])

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

Solution (Python):
import sys

stdin = sys.stdin
def na(): return map(int, stdin.readline().split())

n, ma, mb = na()
abcs = []
for i in range(n):
    abcs.append(list(na()))
I = 9999999999
dp = [[I]*420 for _ in range(420)]
dp[0][0] = 0
sa = 1
sb = 1
for abc in abcs:
    for i in range(sa-1, -1, -1):
        for j in range(sb-1, -1, -1):
            dp[i+abc[0]][j+abc[1]] = min(dp[i+abc[0]][j+abc[1]], dp[i][j] + abc[2])
    sa += abc[0]
    sb += abc[1]

x = ma
y = mb
ret = I
while x< 420 and y < 420:
    ret = min(ret, dp[x][y])
    x += ma
    y += mb

if ret == I:
 print(-1)
else:
 print(ret)

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())

dp = [[[4001 for i in range(411)] for j in range(411)] for l in range(N+1)]

dp[0][0][0] = 0

for i in range(1,N+1):
    for j in range(400):
        for k in range(400):
            if dp[i-1][j][k] == 4001:
                continue
            dp[i][j+a[i-1]][k+b[i-1]] = min(dp[i-1][j][k] + c[i-1],dp[i-1][j+a[i-1]][k+b[i-1]])
            dp[i][j][k] = min(dp[i - 1][j][k], dp[i][j][k])
s = min(400//Ma,400//Mb)

min = 4001
for i in range(1,s+1):
    x = dp[N][i*Ma][i*Mb]
    if x>0 and min > x:
        min = x

if min != 4001:
    print(min)
else:
    print(-1)

Solution (Python):
import sys
 
def solve():
    def dfs(idx, end, value, cost, g):
        if idx == end:
            if cost == 0:
                return

            if value not in g:
                g[value] = cost
            else:
                g[value] = min(g[value], cost)

            return

        a, b, c = table[idx]
        dfs(idx + 1, end, value + b * Ma - a * Mb, cost + c, g)
        dfs(idx + 1, end, value, cost, g)

    N, Ma, Mb = map(int, input().split())
    table = [tuple(map(int, input().split())) for i in range(N)]
 
    g1, g2 = dict(), dict()
    dfs(0, N // 2, 0, 0, g1)
    dfs(N // 2, N, 0, 0, g2)

    inf = 100*40 + 1
    ans = inf
 
    if 0 in g1:
        ans = min(ans, g1[0])
    if 0 in g2:
        ans = min(ans, g2[0])
 
    for v1, c1 in g1.items():
        if -v1 in g2:
            tmp = c1 + g2[-v1]
            ans = min(ans, tmp)
 
    if ans < inf:
        print(ans)
    else:
        print(-1)

        
def debug(x, table):
    for name, val in table.items():
        if x is val:
            print('DEBUG:{} -> {}'.format(name, val), file=sys.stderr)
            return None
 
 
if __name__ == '__main__':
    solve()

Solution (Python):
import sys
 
def solve():
    def dfs(idx, end, value, cost, g):
        if idx == end:
            if cost == 0:
                return

            if value not in g:
                g[value] = cost
            else:
                g[value] = min(g[value], cost)

            return

        a, b, c = table[idx]
        dfs(idx + 1, end, value + b * Ma - a * Mb, cost + c, g)
        dfs(idx + 1, end, value, cost, g)

    N, Ma, Mb = map(int, input().split())
    table = [tuple(map(int, input().split())) for i in range(N)]
 
    g1, g2 = dict(), dict()
    dfs(0, N // 2, 0, 0, g1)
    dfs(N // 2, N, 0, 0, g2)

    inf = 100*40 + 1
    ans = inf
 
    if 0 in g1:
        ans = min(ans, g1[0])
    if 0 in g2:
        ans = min(ans, g2[0])
 
    for v1, c1 in g1.items():
        if -v1 in g2:
            tmp = c1 + g2[-v1]
            ans = min(ans, tmp)
 
    if ans < inf:
        print(ans)
    else:
        print(-1)

        
def debug(x, table):
    for name, val in table.items():
        if x is val:
            print('DEBUG:{} -> {}'.format(name, val), file=sys.stderr)
            return None
 
 
if __name__ == '__main__':
    solve()

Solution (Python):

def solve():
    N, Ma, Mb = map(int, input().split())
    a, b, c = [], [], []

    for i in range(N):
        ai, bi, ci = map(int, input().split())
        a.append(ai)
        b.append(bi)
        c.append(ci)

    nvals = 99 * N * 2 + 1
    inf = 40 * 100 + 1
    dp = [inf] * nvals

    for i in range(N):
        v = Mb * a[i] - Ma * b[i]

        if i == 0:
            dp[v] = c[i]
            continue

        if v > 0:
            for j in range(99 * N, -99 * N + v - 1, -1):
                dp[j] = min(dp[j], dp[j - v] + c[i])
        else:
            for j in range(-99 * N, 99 * N + v + 1):
                dp[j] = min(dp[j], dp[j - v] + c[i])

        dp[v] = min(dp[v], c[i])

    ans = dp[0]

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

if __name__ == '__main__':
    solve()

Solution (Python):

def solve():
    N, Ma, Mb = map(int, input().split())
    a, b, c = [], [], []

    for i in range(N):
        ai, bi, ci = map(int, input().split())
        a.append(ai)
        b.append(bi)
        c.append(ci)

    nvals = 99 * N * 2 + 1
    inf = 40 * 100 + 1
    dp = [[inf] * nvals for i in range(N)]

    for i in range(N):
        v = Mb * a[i] - Ma * b[i]

        if i == 0:
            dp[i][v] = c[i]
            continue

        for j in range(-99 * N, 99 * N + 1):
            if -99 * N <= j - v <= 99 * N:
                dp[i][j] = min(dp[i - 1][j], dp[i - 1][j - v] + c[i])

        dp[i][v] = min(dp[i][v], c[i])

    ans = dp[N - 1][0]

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

if __name__ == '__main__':
    solve()

Solution (Python):

def solve():
    N, Ma, Mb = map(int, input().split())
    a, b, c = [], [], []

    for i in range(N):
        ai, bi, ci = map(int, input().split())
        a.append(ai)
        b.append(bi)
        c.append(ci)

    alim = sum(a)
    blim = sum(b)
    inf = 40 * 100 + 1

    dp = [[inf]*(blim + 1) for i in range(alim + 1)]
    dp[0][0] = 0

    for i in range(N):
        for u in range(alim, a[i] - 1, -1):
            for v in range(blim, b[i] - 1, -1):
                dp[u][v] = min(dp[u][v], dp[u - a[i]][v - b[i]] + c[i])

    ans = inf

    for u in range(1, alim + 1):
        for v in range(1, blim + 1):
            if u * Mb == v * Ma:
                ans = min(ans, dp[u][v])

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

if __name__ == '__main__':
    solve()

Solution (Python):
import sys

def solve():
    N, Ma, Mb = map(int, input().split())
    table = [tuple(map(int, input().split())) for i in range(N)]

    g1 = half_rekkyo(N, Ma, Mb, table, 0, N // 2)
    g2 = half_rekkyo(N, Ma, Mb, table, N // 2, N - N // 2)

    inf = 100 * 40 + 1
    ans = inf

    if 0 in g1:
        ans = min(ans, g1[0])
    if 0 in g2:
        ans = min(ans, g2[0])

    for v1, c1 in g1.items():
        if -v1 in g2:
            tmp = c1 + g2[-v1]
            ans = min(ans, tmp)

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

def half_rekkyo(N, Ma, Mb, table, s, m):
    res = dict()

    for comb in range(1, 2**m):
        v = 0
        cost = 0

        for i in range(m):
            if comb & (1 << i):
                a, b, c = table[s + i]
                v += b * Ma - a * Mb
                cost += c

        if v in res:
            res[v] = min(res[v], cost)
        else:
            res[v] = cost

    return res

def debug(x, table):
    for name, val in table.items():
        if x is val:
            print('DEBUG:{} -> {}'.format(name, val), file=sys.stderr)
            return None


if __name__ == '__main__':
    solve()

Solution (Python):
global N
global Nlist
global Ma
global Mb
global minicost
minicost = 10000000
N, Ma, Mb = map(int,input().split()) 
Nlist = []
for i in range(N):
    a,b,c = map(int,input().split())
    Nlist.append([a,b,c])

def dvector(Masum,Mbsum,cost,vector):
    global Ma
    global Mb
    global Nlist
    global minicost
    if len(vector) == len(Nlist):
        return 0
    dvector(Masum,Mbsum,cost,vector+[0])
    Masum+= Nlist[len(vector)-1][0]
    Mbsum+= Nlist[len(vector)-1][1]
    cost += Nlist[len(vector)-1][2]
    if Mbsum > 0:
        if Masum/Mbsum == Ma/Mb:
            if minicost > cost:
                minicost = cost
    if cost < minicost:
        dvector(Masum,Mbsum,cost,vector+[1])
    return 0
    
dvector(0,0,0,[])
if minicost == 10000000:
    print("-1")
else:
    print(minicost)

Solution (Python):

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

A,B,C = [0]*N,[0]*N,[0]*N

for i in range(N):
  A[i],B[i],C[i] = map(int, input().split())

table = dict()
table[(0,0)] = 0

for a,b,c in zip(A,B,C):
  updates = []
  for e,v in table.items():
    ne = (e[0]+a, e[1]+b)
    if ne not in table or table[ne] > table[e] + c:
      updates.append((ne,table[e]+c))
  table.update(updates)

max_iter = min(sum(A)//Ma, sum(B)//Mb) + 1

try:
  print(min(table[(Ma*i,Mb*i)] for i in range(1,max_iter) if (Ma*i, Mb*i) in table))
except (ValueError, KeyError):
  print(-1)

Solution (Python):
import sys
inf = float('inf')
 
def debug(x, table):
    for name, val in table.items():
        if x is val:
            print('DEBUG:{} -> {}'.format(name, val), file=sys.stderr)
            return None
 
def solve():
    N, Ma, Mb = map(int, input().split())
    wa = [None]
    wb = [None]
    costs = [None]
 
    for i in range(N):
        a, b, c = map(int, input().split())
        wa.append(a)
        wb.append(b)
        costs.append(c)
 
    dp = [[[inf]*(10*N + 1) for j in range(10*N + 1)]
                           for k in range(N + 1)]
 
    
    dp[0][0][0] = 0
 
    for k in range(1, N + 1):
        for a in range(10*N + 1):
            for b in range(10*N + 1):
                dp[k][a][b] = dp[k - 1][a][b]
                if a - wa[k] >= 0 and b - wb[k] >= 0:
                    dp[k][a][b] = min(dp[k][a][b],
                                        dp[k - 1][a - wa[k]][b - wb[k]] + costs[k])
 
    min_c = inf
 
    for a in range(1, 10*N + 1):
        for b in range(1, 10*N + 1):
            if a * Mb == b * Ma:
                min_c = min(min_c, dp[N][a][b])
 
    if min_c == inf:
        ans = -1
    else:
        ans = min_c
 
    print(ans)
 
if __name__ == '__main__':
    solve()

Solution (Python):
from collections import defaultdict
from fractions import Fraction

INF = int(1e14)


def main():
    N, Ma, Mb = map(int, input().split())
    l = []
    for _ in range(N):
        l.append(tuple(map(int, input().split())))

    ans = INF
    dp = [[[INF] * 401 for i in range(401)] for j in range(N + 1)]
    dp[0][0][0] = 0

    max_a, max_b = 1, 1
    for i in range(N):

        for a in range(max_a, -1, -1):
            for b in range(max_b, -1, -1):
                if dp[i][a][b] != INF:
                    dp[i + 1][a + l[i][0]][b + l[i][1]] = min(dp[i + 1][a + l[i][0]][b + l[i][1]], dp[i][a][b] + l[i][2])
                    dp[i + 1][a][b] = min(dp[i + 1][a][b], dp[i][a][b])

                    max_a = max(max_a, a + l[i][0])
                    max_b = max(max_b, b + l[i][1])

    for a in range(1, len(dp[0])):
        for b in range(1, len(dp[1])):
            if a * Mb == b * Ma:
                ans = min(ans, dp[N][a][b])

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

if __name__ == '__main__':
    main()

Solution (Python):
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time

sys.setrecursionlimit(10**7)
inf = 10**20
mod = 10**9 + 7

def LI(): return list(map(int, input().split()))
def II(): return int(input())
def LS(): return input().split()
def S(): return input()


def main():
    n,m1,m2 = LI()
    r = [[inf]*401 for _ in range(401)]
    r[0][0] = 0
    for a,b,c in [LI() for _ in range(n)]:
        for i in range(400-a,-1,-1):
            for j in range(400-b,-1,-1):
                if r[i][j] == inf:
                    continue
                if r[i+a][j+b] > r[i][j] + c:
                    r[i+a][j+b] = r[i][j] + c

    t = inf
    for k in range(1,401):
        k1,k2 = m1*k,m2*k
        if k1 > 400 or k2 > 400:
            break
        if r[k1][k2] < t:
            t = r[k1][k2]

    if t == inf:
        return -1
    return t


print(main())

Solution (Python):
import numpy as np
import copy

if __name__=="__main__":
    inputs_number  = lambda : [int(x) for x in input().split()]
    N, Ma, Mb = inputs_number()
    drugs = [inputs_number() for i in range(N)]
    inf = 100*N + 1
    dp = np.ones((2,N*10+1,N*10+1)).astype(np.int32) * inf
    dp = dp.tolist()
    dp[0][0][0] = 0.0

    for i in range(N):
        for ca in range(10*i+1):
            for cb in range(10*i+1):
                if(dp[0][ca][cb]==inf):
                    continue
                dp[1][ca][cb]=min([dp[1][ca][cb], dp[0][ca][cb]])
                dp[1][ca+drugs[i][0]][cb+drugs[i][1]]=min([dp[1][ca+drugs[i][0]][cb+drugs[i][1]], dp[0][ca][cb]+drugs[i][2]])
        dp[0] = copy.copy(dp[1])
        dp[1] = (np.ones((N*10+1,N*10+1)).astype(np.int32) * inf).tolist()
    ans = inf
    for ca in range(1, N*10+1):
        for cb in range(1, N*10+1):
            if(Ma*cb==Mb*ca and dp[0][ca][cb]<ans):
                ans = dp[0][ca][cb]
    if(ans==inf):
        ans = -1
    print(int(ans))

Solution (Python):


import itertools


def compute(n, m_a, m_b, a, b, c):
    max_a, max_b, max_c = max(a), max(b), max(c)
    inf = n * max_c * 2
    dp = [[[inf for _ in range(n * max_b + 1)]
          for _ in range(n * max_a + 1)] for _ in range(n + 1)]
    dp[0][0][0] = 0
    g = itertools.product(range(n), range(n * max_a + 1), range(n * max_b + 1))
    for i, wa, wb in g:
        if dp[i][wa][wb] == inf:
            continue
        dp[i + 1][wa][wb] = min(dp[i + 1][wa][wb], dp[i][wa][wb])
        dp[i + 1][wa + a[i]][wb + b[i]] = min(dp[i + 1][wa + a[i]][wb + b[i]],
                                              dp[i][wa][wb] + c[i])
    h = itertools.product(range(1, n * max_a + 1), range(1, n * max_b + 1))
    ans = min((dp[n][wa][wb] for wa, wb in h if wa * m_b == wb * m_a),
              default=inf)
    return ans if ans != inf else -1


def main():
    n, m_a, m_b = (int(x) for x in input().split())
    a, b, c = ([int(i) for i in r] for r in
               zip(*(input().split() for _ in range(n))))
    print(compute(n, m_a, m_b, a, b, c))


if __name__ == '__main__':
    main()

Solution (Python):
from heapq import heappush, heappop
n, ma, mb = map(int, raw_input().split())
dp = {(0, 0): 0}
INF = 10**18
for i in xrange(n):
    a, b, c = map(int, raw_input().split())
    for x, y in sorted(dp.keys())[::-1]:
        dp[x+a, y+b] = min(dp.get((x+a, y+b), INF), dp[x, y] + c)
ans = INF
for x, y in dp:
    if x*mb == y*ma > 0:
        ans = min(ans, dp[x, y])
print -1 if ans==INF else ans

Solution (Python):
from collections import defaultdict

N, MA, MB = map(int, raw_input().split())
X = [map(int, raw_input().split()) for _ in range(N)]

dp = defaultdict()

dp[(0, 0)] = 0
for a, b, c in X:
    dp2 = defaultdict()
    for sa, sb in dp:
        if (sa+a, sb+b) not in dp:
            dp2[(sa+a, sb+b)] = dp[(sa, sb)] + c
        elif dp[(sa+a, sb+b)] > dp[(sa, sb)] + c:
            dp2[(sa+a, sb+b)] = dp[(sa, sb)] + c
    for (na, nb) in dp2:
        dp[(na, nb)] = dp2[(na, nb)]

a, b = MA, MB
ans = 100000
while a <= 400 and b <= 400:
    if (a, b) in dp:
        ans = min(ans, dp[(a, b)])
    a += MA
    b += MB

if ans == 100000:
    print -1
else:
    print ans

Solution (Python):
INF = 1010101010

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

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

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

        for A in range(401):
            for B in range(401):
                nx[A][B] = min(nx[A][B], dp[A][B])
                if A+a<=400 and B+b<=400:
                    nx[A+a][B+b] = min(nx[A+a][B+b], dp[A][B]+c)

        dp = nx[:]

    ans = INF
    for A in range(1,401):
        for B in range(1,401):
            if Ma*B == Mb*A:
                ans = min(ans, dp[A][B])

    return -1 if ans == INF else ans

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

Solution (Python):


import re
from scipy import integrate
import math
from operator import itemgetter
from collections import defaultdict as dd
from collections import Counter
from collections import deque

import numpy as np
import itertools

import heapq

from copy import deepcopy as dcopy
import fractions
def main():
    global N, ma, mb
    N, ma, mb = map(int, input().split())
    shop = [list(map(int, input().split())) for n in range(N)]

    status = dd(int)
    status[(0,0)] = 0
    minimum = 100000
    for product in shop:
        
        old_status = dcopy(status)
        for s, v in old_status.items():
            key = (s[0]+product[0], s[1]+product[1])
            value = v + product[2]
            if not key in status:
                status[key] = value
                if check(key) and value < minimum:
                    minimum = value
            elif status[key] > value:
                status[key] = value
                if check(key) and value < minimum:
                    minimum = value

    if minimum == 100000:
        print(-1)
    else:
        print(minimum)

def check(key):
    c = fractions.gcd(key[0], key[1])
    if key[0]/c == ma and key[1]/c == mb:
        return True
    else:
        return False

if __name__ == "__main__":
    try:
        import test
        test.test()
    except:
        main()

Solution (Python):
import copy

data = raw_input()
n,ma,mb = map(int,data.split(" "))

ans = {}

for x in range(n):
  data = raw_input()
  a,b,c = map(int,data.split(" "))

  q = a*mb - b*ma
  d = []

  for x in ans:
    d.append( [x,ans[x]] )
  for x in d:
    if x[0]+q in ans:
      ans[ x[0]+q ] = min(ans[x[0]+q], x[1]+c )
    else:
      ans[ x[0]+q ] = x[1]+c
  if q in ans:
    ans[q] = min(ans[q],c)
  else:
    ans[q] = c

if 0 in ans:
  print ans[0]
else:
  print -1

Solution (Python):
import sys

def debug(x, table):
    for name, val in table.items():
        if x is val:
            print('DEBUG:{} -> {}'.format(name, val), file=sys.stderr)
            return None

def solve():
    N, Ma, Mb = map(int, input().split())
    a_w = []
    b_w = []
    costs = []

    for i in range(N):
        a, b, c = map(int, input().split())
        a_w.append(a)
        b_w.append(b)
        costs.append(c)

    dp = [[[-1]*(10*N + 1) for j in range(10*N + 1)]
            for k in range(2)]

    dp[0][0][0] = 0
    dp[1][0][0] = 0

    for i in range(N):
        for a in range(10*N + 1):
            for b in range(10*N + 1):
                if a - a_w[i] >= 0 and b - b_w[i] >= 0:
                    if dp[0][a - a_w[i]][b - b_w[i]] >= 0:
                        if dp[1][a][b] == -1:
                            dp[1][a][b]= dp[0][a - a_w[i]][b - b_w[i]] + costs[i]
                        else:
                            min_ = min(dp[1][a][b],
                                       dp[0][a - a_w[i]][b - b_w[i]] + costs[i])
                            dp[1][a][b] = min_
        
        for k in range(10*N + 1):
            dp[0][k] = dp[1][k][:]

        
            


    min_cost = float('inf')

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

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

    print(ans)


if __name__ == '__main__':
    solve()

Solution (Python):
import fractions, copy, collections

if __name__ == '__main__':
    n, ma, mb = map(int, input().split())
    rows = [map(int, input().split()) for _ in range(n)]

    ht = {(0, 0) : 0}
    for a, b, c in rows:
        temp = copy.deepcopy(ht)
        for x, y in ht:
            if not (x + a, y + b) in ht or ht[(x, y)] + c < ht[(x + a, y + b)]: temp[(x + a, y + b)] = ht[(x, y)] + c
        ht = temp
    
    ans = float('inf')
    for a, b in ht:
        if b != 0 and fractions.Fraction(ma, mb) == fractions.Fraction(a, b): ans = min(ans, ht[(a, b)])
    
    print(-1 if ans == float('inf') else ans)

Solution (Python):



from fractions import gcd

def readln():
    _res = list(map(int,str(input()).split(' ')))
    return _res

def push(k,v):
    if k in f:
        f[k] = min(f[k],v)
    else:
        f[k] = v

def add(k,v):
    es = []
    for e in f:
        es.append([e,f[e]])
    for ee in es:
        push(ee[0]+k,ee[1]+v)
    push(k,v)

a = readln()
n,x,y = a[0],a[1],a[2]
f = {}
for i in range(0,n):
    a = readln()
    add(a[0]*y-a[1]*x,a[2])
if 0 in f:
    print(f[0])
else:
    print('-1')

Solution (Python):
import copy

N, Ma, Mb = [int(n) for n in input().split()]
pd = {(0,0):0}
for i in range(N):
    a, b, c = [int(n) for n in input().split()]
    pdcopy = copy.deepcopy(pd)
    for k, v in pdcopy.items():
        nk = (k[0]+a, k[1]+b)
        if nk in pd:
            if pd[nk] > v + c :
                pd[nk] = v + c
        else:
            pd[nk] = v + c

mp = 1000000
for i in range(1,401):
    if (Ma*i, Mb*i) in pd:
        mp = min(pd[(Ma*i, Mb*i)], mp)

if mp == 1000000:
    print(-1)
else:
    print(mp)

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

DP = [[10000 for _ in range(500)] for _ in range(500)]
DP[0][0]=0
for i in range(n):
    for j in reversed(range(400)):
        for k in reversed(range(400)):
            if DP[j][k]==10000:continue
            DP[j+G[i][0]][k+G[i][1]] = min(DP[j][k]+G[i][2],DP[j+G[i][0]][k+G[i][1]])

ans=10000
for i in range(1,min(400//ma,400//mb)+1):
    ans=min(ans,DP[ma*i][mb*i])

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

Solution (Python):
n,ma,mb=map(int,raw_input().split())
abc=[map(int,raw_input().split()) for  _ in xrange(n)]
dp=[[[10**5]*(n*10+1) for _ in xrange(n*10+1)] for _ in xrange(n+1)]
for i in xrange(n):
    dp[i][0][0]=0
for i in xrange(n):
    for j in range(n*10+1):
        for k in xrange(n*10+1):
            a,b,c=abc[i][0],abc[i][1],abc[i][2]
            if j-a<0 or k-b<0:
                dp[i+1][j][k]=min(dp[i+1][j][k],dp[i][j][k])
            else:
                dp[i+1][j][k]=min(dp[i][j][k],dp[i+1][j][k],dp[i][j-a][k-b]+c)
i=1
ans=10**5
while ma*i<=n*10 and mb*i<=n*10:
    if dp[n][ma*i][mb*i]!=10**5:
        ans=min(ans,dp[n][ma*i][mb*i])
    i+=1
if ans==10**5:
    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())

M = 401
INF = 10 ** 15
min_cost = [[INF] * M for k in range(M)]
s = set()
min_cost[0][0] = 0
s.add((0, 0))

for k in range(n):
    ss = set(s)
    for i, j in reversed(sorted(s)):
        if i + a[k] < M and j + b[k] < M:
            cc = min_cost[i][j] + c[k]
            if cc < min_cost[i + a[k]][j + b[k]]:
                ss.add((i + a[k], j + b[k]))
                min_cost[i + a[k]][j + b[k]] = cc
    s = ss

res = INF
for i in range(1, M):
    for j in range(1, M):
        if i * mb == j * ma:
            if min_cost[i][j] < res:
                res = min_cost[i][j]

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

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

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

M = 1 + max(sum([ a for a, b, c in G ]),
            sum([ b for a, b, c in G ]) )
INF = 1000000000
dp = [INF] * (M * M)
dp[0] = 0
for a, b, c in G:
  for i in reversed(range(0, M - a)):
    for j in reversed(range(0, M - b)):
      dp[(i+a)*M+(j+b)] = min(dp[(i+a)*M+(j+b)], dp[i*M+j] + c)
ans = INF
x = 1
while Ma * x < M and Mb * x < M:
  ans = min(ans, dp[Ma * x * M + Mb * x])
  x += 1
if ans >= INF:
  ans = -1
print(ans)

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

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

M = 1 + min(sum([ a for a, b, c in G ]),
            sum([ b for a, b, c in G ]) )
INF = 1000000000
dp = [INF] * (M * M)
dp[0] = 0
for a, b, c in G:
  for i in reversed(range(0, M - a)):
    for j in reversed(range(0, M - b)):
      dp[(i+a)*M+(j+b)] = min(dp[(i+a)*M+(j+b)], dp[i*M+j] + c)
ans = INF
x = 1
while Ma * x < M and Mb * x < M:
  ans = min(ans, dp[Ma * x * M + Mb * x])
  x += 1
if ans >= INF:
  ans = -1
print(ans)

Solution (Python):
from collections import defaultdict

n,ma,mb=map(int,input().split())
f=defaultdict(lambda:float('inf'))
for _ in range(n):
    a,b,c=map(int,input().split())
    t=f.copy()
    t[a,b]=min(t[a,b],c)
    for k,v in f.items():
        ka,kb=k[0]+a,k[1]+b
        t[ka,kb]=min(t[ka,kb],v+c)
    f=t

costs=[f[a,b] for a,b in f if a*mb==b*ma]
print(min(costs) if costs else -1)

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

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

M = 1 + min(sum([ a for a, b, c in G ]),
            sum([ b for a, b, c in G ]) )
INF = 1000000000
dp = [INF] * (M * M)
dp[0] = 0
for a, b, c in G:
  i = M - a - 1
  while i >= 0:
    j = M - b - 1
    while j >= 0:
      dp[(i+a)*M+(j+b)] = min(dp[(i+a)*M+(j+b)], dp[i*M+j] + c)
      j -= 1
    i -= 1

ans = INF
x = 1
while Ma * x < M and Mb * x < M:
  ans = min(ans, dp[Ma * x * M + Mb * x])
  x += 1
if ans >= INF:
  ans = -1
print(ans)

Solution (Python):
N, ma, mb = map(int, raw_input().split())
A = [map(int, raw_input().split()) for _ in xrange(N)]

if N == 1:
    if ma * A[0][0] == mb * A[0][1]:
        print A[0][2]
    else:
        print -1
    exit()

n = N / 2
m = N / 2 + N % 2

B = [[0, 0, 0] for _ in xrange(2**n)]

for i in xrange(2**n):
    for j in xrange(n):
        if i & (1 << j):
            B[i][0] += A[j][0]
            B[i][1] += A[j][1]
            B[i][2] += A[j][2]

d = {}
ans = float('inf')

for i in xrange(2**m):
    a = 0
    b = 0
    c = 0
    for j in xrange(m):
        if i & (1 << j):
            a += A[n+j][0]
            b += A[n+j][1]
            c += A[n+j][2]
    x = ma * b - mb * a
    if x == 0 and c > 0:
        ans = min(ans, c)
    if x in d:
        d[x] = min(d[x], c)
    else:
        d[x] = c

for a, b, c in B:
    x = mb * a - ma * b
    if x == 0 and c > 0:
        ans = min(ans, c)
    if x in d and c + d[x] > 0:
        ans = min(ans, c + d[x])
print ans if ans != float('inf') else -1

Solution (Python):
n,ma,mb = map(int, input().split())
p = []
for i in range(n):
    a,b,c = map(int, input().split())
    p.append((a,b,c))

r = [[40001 for j in range(401)] for i in range(401)]
r[0][0] = 0
for i in range(n):
    for j in range(400 - 10*i, -1, -1):
        for k in range(400 - 10*i, -1, -1):
            if 40001 > r[j][k]:
                r[j + p[i][0]][k + p[i][1]] = min(r[j + p[i][0]][k + p[i][1]], r[j][k]+p[i][2])
min_v = 40001
ia = ma
ib = mb
flag  =False
while ia <= 400 and ib<=400:
    if 40001 > r[ia][ib] > 0:
        min_v = min(min_v,  r[ia][ib])
        flag = True
    ia += ma
    ib += mb
        
if not flag:
    print(-1)
else:
    print(min_v)