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.



Sample input:
3 1 1
1 2 1
2 1 2
3 3 10


Sample output:
3

Submission status: Accepted

Solution code:

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

Submission status: Accepted

Solution code:

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

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:

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)

Submission status: Accepted

Solution code:
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)]
 
    # debug(dp, locals())
    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()

Submission status: Accepted

Solution code:
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()

Submission status: Accepted

Solution code:
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())

Submission status: Accepted

Solution code:
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))

Submission status: Accepted

Solution code:
#!/usr/bin/env python3

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

Submission status: Accepted

Solution code:
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

Submission status: Accepted

Solution code:
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

Submission status: Accepted

Solution code:
# coding: utf-8

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:
        # buy
        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()# }}}

Submission status: Accepted

Solution code:
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

Submission status: Accepted

Solution code:
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][:]

        # for i in range(10*N + 1):
            # print(*dp[0][i], file=sys.stderr)


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

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

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

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:

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)

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
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

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
import sys,copy,math,heapq,itertools as it,fractions,re,bisect,collections as coll

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

N, Ma, Mb = map(int, raw_input().split())
abc = [map(int, raw_input().split()) for i in xrange(N)]

dp = [[0]*405 for i in xrange(405)]

for a, b, c in abc:
    for i in xrange(404-a, -1, -1):
        for j in xrange(404-b, -1, -1):
            if dp[i][j]:
                if dp[i + a][j + b] == 0: dp[i + a][j + b] = dp[i][j] + c
                else: dp[i + a][j + b] = min(dp[i + a][j + b], dp[i][j] + c)
    if dp[a][b] == 0: dp[a][b] = c
    else: dp[a][b] = min(dp[a][b], c)

ans = inf
for i in xrange(1, 405):
    for j in xrange(1, 405):
        g = gcd(i, j)
        if i/g == Ma and j/g == Mb and dp[i][j]:
            ans = min(ans, dp[i][j])

print ans if ans < inf else -1

Submission status: Accepted

Solution code:

N, Ma, Mb = [int(_) for _ in input().split()]
T = [[int(_) for _ in input().split()] for i in range(N)]

dp = [[float('inf') for i in range(401)] for i in range(401)]
dp[0][0] = 0

sum_a = 0
sum_b = 0
for x in range(N):
    a, b, c = T[x]
    sum_a += a
    sum_b += b
    for i in list(range(a, sum_a+1))[::-1]:
        for j in list(range(b, sum_b+1))[::-1]:
            dp[i][j] = min(dp[i][j], dp[i-a][j-b]+c)

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

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

Submission status: Accepted

Solution code:
import sys

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


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)

Submission status: Runtime Error

Solution code:
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]
                    #print(i,a,b,temp[a][b],prev[a-cur[0]][b-cur[1]])
                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,11):
        if i*ma>10 or i*mb>10:
            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)
    print(dp[n])

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

Submission status: Runtime Error

Solution code:
import math
N, Ma, Mb = map(int, input().split())
cost = [[0] * 10 for _ in range(10)]
for _ in range(N):
    a, b, c = map(int, input().split())
    a -= 1
    b -= 1
    cost[a][b] = c

min_cost = 10 ** 9 + 7
for k in range(N):
    for i in range(N):
        for j in range(N):
            g = math.gcd(i + 1 + k + 1, k + 1 + j + 1)
            if (i + 1 + k + 1) // g == Ma and (k + 1 + j + \
                1) // g == Mb and cost[i][k] + cost[k][j] != 0:
                # print(cost[i][k] + cost[k][j])
                min_cost = min(min_cost, cost[i][k] + cost[k][j])


if min_cost == 10 ** 9 + 7:
    print(-1)
else:
    print(min_cost)

Submission status: Runtime Error

Solution code:
import numpy as np
from numba import njit

@njit
def main(n,ma,mb,abc):
    inf=10**5
    cost=inf*np.ones((401,401))
    maxa=np.sum(np.transpose[abc][0])
    maxb=np.sum(np.transpose[abc][1])

    left=4*n//8
    right=n
    cnt=right-left

    for i in range(2**cnt):
        ta=0
        tb=0
        tc=0
        for j in range(cnt):
            if (i>>j)&1==1:
                a,b,c=abc[left+j]
                ta+=a
                tb+=b
                tc+=c
        
        cost[ta,tb]=min(cost[ta,tb],tc)
    
    ans=inf

    for i in range(1,401):
        targeta=ma*i
        targetb=mb*i
        if targeta>maxa or targetb>maxb:
            break

        for j in range(2**left):
            ta=0
            tb=0
            tc=0
            for k in range(left):
                if (j>>k)&1==1:
                    a,b,c=abc[k]
                    ta+=a
                    tb+=b
                    tc+=c
        
            ua=targeta-ta
            ub=targetb-tb

            if 0<=ua<=400 and 0<=ub<=400 and cost[ua,ub]!=inf:
                ans=min(ans,tc+cost[ua,ub])
    
    if ans==inf:
        return -1
    else:
        return int(ans)

n,ma,mb=map(int,input().split())
abc=np.array([list(map(int,input().split())) for _ in range(n)])
print(main(n,ma,mb,abc))

Submission status: Runtime Error

Solution code:
N, Ma, Mb = map(int, input().split())
Med = [tuple(map(int, input().split())) for _ in range(N)]
INF = 100000
from collections import defaultdict as dd
dp =  [dd(lambda:INF) for _ in range(N+1)]#dp[i,j]:Aがiグラム、Bがjグラムの時の最小予算
for n in range(1,N+1):
    a,b,c = Med[n-1]
    dp[n-1][0,0] = 0
    for (i,j),value in dp[n-1].items():
        dp[n][i+a,j+b] = min(dp[n-1][i+a,j+b],value+c)

ans = INF
for (i,j),value in dp[N].items():
    if i == j == 0:
        continue
    if i*Mb == j*Ma:
        ans = min(ans, value)
print(ans if ans != INF else -1)

Submission status: Runtime Error

Solution code:
N, Ma, Mb = map(int, input().split())
Med = [tuple(map(int, input().split())) for _ in range(N)]
N *= 100
INF = 100000
dp = [[INF]*N+1 for _ in range(N+1)] #dp[i,j]:Aがiグラム、Bがjグラムの時の最小予算
dp[0][0] = 0 
from itertools import product as prd
R = lambda x:reversed(range(x,N+1))
for a,b,c in Med:
    for i,j in prd(R(a),R(b)):
        dp[i][j] = min(dp[i][j], dp[i-a][j-b]+c)

ans = INF
for i,j in prd(R(1),R(1)):
    if i*Mb == j*Ma:
        ans = min(ans, dp[i][j])
print(ans if ans != INF else -1)

Submission status: Runtime Error

Solution code:
from itertools import groupby, accumulate, product, permutations, combinations
def solve():
  ans = float('inf')
  N, A, B = map(int, input().split())
  mae = [list(map(int, input().split())) for _ in range((N+1)//2)]
  usiro = [list(map(int, input().split())) for _ in range(N-(N+1)//2)]
  if N==1:
    a,b,c = mae[0]
    if a*B==b*A:
      return c
    return -1
  mae_lis = [[float('inf')]*201 for _ in range(201)]
  for p in product([0,1],repeat=(N+1)//2):
    a,b,c = 0,0,0
    for i in range(N//2):
      if p[i]==1:
        a += mae[i][0];b += mae[i][1];c += mae[i][2]
      mae_lis[a][b] = min(mae_lis[a][b],c)
  usiro_lis = [[float('inf')]*201 for _ in range(201)]
  for p in product([0,1],repeat=N-(N+1)//2):
    a,b,c = 0,0,0
    for i in range(N//2):
      if p[i]==1:
        a += usiro[i][0];b += usiro[i][1];c += usiro[i][2]
      usiro_lis[a][b] = min(usiro_lis[a][b],c)
  for i in range(1,201):
    for j in range(1,201):
      c = mae_lis[i][j]
      if c==float('inf'):
        continue
      for k in range(1,201):
        if (i+k)*B%A!=0:
          continue
        l = (i+k)*B//A - j
        if l<=0:
          continue
        ans = min(ans,c+usiro_lis[k][l])
  return ans if ans<float('inf') else -1
print(solve())