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: Time Limit Exceeded

Solution code:
import random
import bisect
import math

nn, ma, mb = [int(i) for i in input().split()]
a =  [0 for i in range(nn)]
b =  [0 for i in range(nn)]
c =  [0 for i in range(nn)]
for i in range(nn):
     a[i], b[i], c[i] = [int(i) for i in input().split()]

option = 0     # 0:PSO 1:CFA 2:CFArank
max_or_min = 0 # 0:minimize 1:maxmize
dimension = nn
iter=1

N = 50 #粒子の数
T = 1100 #世代数(ループの回数)
maximum=1
minimum=0


#--------粒　子　群　最　適　化------------------------------

#評価関数
def criterion(x):

    z = sum([c[i] * x[i] for i in range(dimension)])
    if mb * sum([a[i] * x[i] for i in range(dimension)]) - ma * sum([b[i] * x[i] for i in range(dimension)]) != 0 or sum(x) == 0:
        z = 1000000
    return z

#粒子の位置の更新を行う関数
def update_position(x, v, x_min, x_max):
#    new_x = [x_min[i] if x[i]+ v[i] < x_min[i] else x_max[i] if x[i]+ v[i] > x_max[i] else x[i]+ v[i] for i in range(dimension)]
    new_x = [1 if random.uniform(0, 1)< 1/(1+math.e**(-v[i])) else 0 for i in range(dimension)]
    return new_x

#粒子の速度の更新を行う関数
def update_velocity(x, v, p, g, w, ro_max=1.0, c1=2.00, c2=0.75):
    #パラメーターroはランダムに与える
    phi=c1+c2
    K=2/abs(2-phi-(phi*phi-4*phi)**0.5)
    
    #粒子速度の更新を行う
    if option!=0:
        new_v = [K * ( w * v[i] + c1 * random.uniform(0, ro_max) * (p[i] - x[i]) + c2 * random.uniform(0, ro_max) * (g[i] - x[i]) ) for i in range(dimension)]
    else:
        new_v = [w * v[i] + c1 * random.uniform(0, ro_max) * (p[i] - x[i]) + c2 * random.uniform(0, ro_max) * (g[i] - x[i]) for i in range(dimension)]

    return new_v

def main():
    w = 1.0
    w_best, w_worst = 1.25, 0.25
    x_min = [minimum for i in range(dimension)]
    x_max = [maximum for i in range(dimension)]
    
    #粒子位置, 速度, パーソナルベスト, グローバルベストの初期化を行う
    ps = [[random.randint(x_min[j], x_max[j]) for j in range(dimension)] for i in range(N)]
    vs = [[0.0 for j in range(dimension)] for i in range(N)]

    personal_best_positions = ps[:] 
    personal_best_scores = [criterion(p) for p in ps]

    if max_or_min == 1:
        best_particle = personal_best_scores.index(max(personal_best_scores))
    elif max_or_min == 0:
        best_particle = personal_best_scores.index(min(personal_best_scores))
    global_best_position = personal_best_positions[best_particle][:]

    for t in range(T):
        for n in range(N):
            x = ps[n][:]
            v = vs[n][:]
            p = personal_best_positions[n][:]

            if option>=2:
                best_list = sorted(personal_best_positions)
                mu = bisect.bisect_left( best_list, p ) + 1
                w = w_best - mu * (w_best - w_worst) / (N - 1)


            #粒子の位置の更新を行う
            new_x = update_position(x, v, x_min, x_max)
            ps[n] = new_x[:]

            #粒子の速度の更新を行う
            new_v = update_velocity(new_x, v, p, global_best_position, w)
            vs[n] = new_v[:]

            #評価値を求め, パーソナルベストの更新を行う
            score = criterion(new_x)

            if max_or_min == 1:
                if score > personal_best_scores[n]:
                    personal_best_scores[n] = score
                    personal_best_positions[n] = new_x[:]
            elif max_or_min == 0:
                if score < personal_best_scores[n]:
                    personal_best_scores[n] = score
                    personal_best_positions[n] = new_x[:]

        #グローバルベストの更新を行う
        if max_or_min == 1:
            best_particle = personal_best_scores.index(max(personal_best_scores))
            global_best_position = personal_best_positions[best_particle][:]

        elif max_or_min == 0:
            best_particle = personal_best_scores.index(min(personal_best_scores))
            global_best_position = personal_best_positions[best_particle][:]
        f.write(str(max(personal_best_scores))+"\n")
    #最適解
    if max_or_min == 1:
        return max(personal_best_scores)
    elif max_or_min == 0:
        #print(global_best_position)
        return min(personal_best_scores)

#--------------------------------------------------------------
with open('test_'+ str(option)+".txt", 'w') as f:
    
  if max_or_min == 1:
    best=-float("inf")
    for i in range(iter):
        best=max(best, main())

  elif max_or_min == 0:
    best=float("inf")
    for i in range(iter):
        best=min(best, main())
if best == 1000000:
    print(-1)
else:
    print(best)

Submission status: Time Limit Exceeded

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

dp = [[[float("inf") for _ in range(401)] for _ in range(401)] for _ in range(N+1)]
dp[0][0][0] = 0



for i in range(N):
  a,b,c = map(int, input().split())
  for j in range(401):
    for k in range(401):
      if j-a < 0 or k-b < 0:
        dp[i+1][j][k] = dp[i][j][k]
      else:
        dp[i+1][j][k] = min(dp[i][j][k], dp[i][j-a][k-b] + c)

        
ans = float("inf")
        
a = Ma
b = Mb
while(a < 401 and b < 401):
  ans = min(ans, dp[N][a][b])
  a += Ma
  b += Mb
  
if ans == float("inf"):
  print(-1)
else:
  print(ans)

Submission status: Time Limit Exceeded

Solution code:
N, Ma, Mb = map(int, input().split())
abc = [list(map(int, input().split())) for _ in range(N)]
result = None

for i in range(1, 2 ** N):
    bin_i = bin(i)[2:]
    bin_i = '0' * (N - len(bin_i)) + bin_i
    a = 0
    b = 0
    price = 0
    for j in range(N):
        if bin_i[j] == '1':
            a += abc[j][0]
            b += abc[j][1]
            price += abc[j][2]

    if a / b == Ma / Mb:
        if result:
            result = min(result, price)
        else:
            result = price

print(result if result else -1)

Submission status: Time Limit Exceeded

Solution code:
N, Ma, Mb= (int(i) for i in input().split())
L = []
for i in range(N):
    a, b, c = (int(i) for i in input().split())
    L.append((a, b, c))

dp= [[[float("inf")] * (10 * N + 11) for a in range(10 * N + 11) ] for i in range(N + 1)]
dp[0][0][0] = 0

for i in range(N):
    a, b, c = L[i]
    for ca in range(10 * N + 1):
        for cb in range(10 * N + 1):
            dp[i+1][ca][cb] = min(dp[i+1][ca][cb], dp[i][ca][cb])
            dp[i+1][ca + a][cb + b] = min(dp[i+1][ca + a][cb + b], dp[i][ca][cb] + c)

reslis = []
ra, rb = (Ma, Mb)
while ra <= 10 * N and rb <= 10 * N:
    reslis.append(dp[N][ra][rb])
    ra += Ma
    rb += Mb

reslis.sort()
res = reslis[0]
if res == float("inf"):
    print(-1)
else:
    print(res)

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
n,ma,mb = map(int, input().split())
abc = []
sa = 0
sb = 0
for _ in range(n):
    a,b,c = map(int, input().split())
    sa += a
    sb += b
    abc.append((a,b,c))
inf = 10**5
dp = [[[inf for _ in range(sb+1)] for _ in range(sa+1)] for _ in range(n+1)]
dp[0][0][0] = 0
for i in range(n):
    a,b,c = abc[i]
    for ai in range(sa+1):
        for bi in range(sb+1):
            dp[i+1][ai][bi] = min(dp[i+1][ai][bi], dp[i][ai][bi])
            if ai+a<sa+1 and bi+b<sb+1:
                dp[i+1][ai+a][bi+b] = min(dp[i+1][ai+a][bi+b], dp[i][ai][bi]+c)
# print(dp)

res = inf
for ai in range(1,sa+1):
    for bi in range(1,sb+1):
        if ma*bi==mb*ai:
            res = min(res, dp[n][ai][bi])
if res == inf:
    print(-1)
else:
    print(res)

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
n,ma,mb = map(int, input().split())
abc = []
for _ in range(n):
    a,b,c = map(int, input().split())
    abc.append((a,b,c))
inf = 10**5
dp = [[[inf for _ in range(n*10+1)] for _ in range(n*10+1)] for _ in range(n+1)]
dp[0][0][0] = 0
for i in range(n):
    a,b,c = abc[i]
    for ai in range(n*10+1):
        for bi in range(n*10+1):
            dp[i+1][ai][bi] = min(dp[i+1][ai][bi], dp[i][ai][bi])
            if ai+a<n*10+1 and bi+b<n*10+1:
                dp[i+1][ai+a][bi+b] = min(dp[i+1][ai+a][bi+b], dp[i][ai][bi]+c)
# print(dp)

res = inf
for ai in range(1,n*10+1):
    for bi in range(1,n*10+1):
        if ma*bi==mb*ai:
            res = min(res, dp[n][ai][bi])
if res == inf:
    print(-1)
else:
    print(res)

Submission status: Time Limit Exceeded

Solution code:
N,Ma,Mb=map(int,input().split())
dp=[[[10**9]*401 for i in range(401)] for i in range(N)]
for i in range(N):
  a,b,c=map(int,input().split())
  if i==0:
    dp[0][a][b]=c
    dp[0][0][0]=0
  else:
    for p in range(401):
      for q in range(401):
        if p>=a and q>=b:
          dp[i][p][q]=min(dp[i-1][p][q],dp[i-1][p-a][q-b]+c)
        else:
          dp[i][p][q]=dp[i-1][p][q]
ans=10**9
for a in range(1,401):
  if Mb*a/Ma<=400 and Mb*a%Ma==0:
    ans=min(ans,dp[N-1][a][Mb*a//Ma])
if ans==10**9:
  print(-1)
else:
  print(ans)

Submission status: Time Limit Exceeded

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

mix=set([(0,0,0)])
rate=Ma/Mb
ans=10**9
for i in range(N):
    a,b,c=list(map(int,input().split()))
    tmp=mix.copy()
    for x in tmp:
        d=x[0]+a
        e=x[1]+b
        f=x[2]+c
        mix.add((d, e, f))
        if d/e==Ma/Mb and f<ans:
            ans=f
if ans==10**9:
    ans=-1
print(ans)

Submission status: Time Limit Exceeded

Solution code:
# https://beta.atcoder.jp/contests/abc054/tasks/abc054_d

N,Ma,Mb = map(int,input().split())
qa=Ma
qb=Mb
candidates = []
while qa <= N*10 and qb <= N*10:
    candidates.append((qa,qb))
    qa += Ma
    qb += Mb
a = []
b = []
c = []
for _ in range(N):
    A,B,C = map(int,input().split())
    a.append(A)
    b.append(B)
    c.append(C)
#DP
INF = 10**8
dp = [[[INF for _ in range(N*10+1)] for _ in range(N*10+1)] for _ in range(N+1)]
dp [0][0][0] = 0
for i in range(1,N+1):
   for j in range(N*10+1) :
       for k in range(N*10+1):
           x = j - a[i-1]
           y = k - b[i-1]
           if x>=0 and y>=0:
               dp[i][j][k] = min(dp[i-1][j][k],dp[i-1][x][y]+c[i-1])
           else:
               dp[i][j][k] = dp[i-1][j][k]
#Answer
cost = INF
for x,y in candidates:
    cost = min(cost,dp[N][x][y])
if cost == INF:
    print(-1)
else:
    print(cost)

Submission status: Time Limit Exceeded

Solution code:
import itertools
N, Ma, Mb = map(int, input().split())
r = Ma/Mb
costlist = []
data = [list(map(int, input().split())) for i in range(N)]
for i in range(1, max(N+1, 11)):
    combination = list(itertools.combinations(data, i))
    for k in range(len(combination)):
        a_tot = 0
        b_tot = 0
        c_tot = 0
        for j in range(len(combination[k])):
            a_tot += combination[k][j][0]
            b_tot += combination[k][j][1]
            c_tot += combination[k][j][2]
        if a_tot/b_tot == r:
            costlist.append(c_tot)
if costlist == []:
    print(-1)
else:
    print(min(costlist))

Submission status: Time Limit Exceeded

Solution code:
import itertools
N, Ma, Mb = map(int, input().split())
r = Ma/Mb
costlist = []
data = [list(map(int, input().split())) for i in range(N)]
for i in range(1, N+1):
    combination = list(itertools.combinations(data, i))
    for k in range(len(combination)):
        a_tot = 0
        b_tot = 0
        c_tot = 0
        for j in range(len(combination[k])):
            a_tot += combination[k][j][0]
            b_tot += combination[k][j][1]
            c_tot += combination[k][j][2]
        if a_tot/b_tot == r:
            costlist.append(c_tot)
if costlist == []:
    print(-1)
else:
    print(min(costlist))

Submission status: Time Limit Exceeded

Solution code:
import copy
N,Ma,Mb = map(int,input().split())
qa=Ma
qb=Mb
candidates = []
while qa <= 400 and qb <= 400:
    candidates.append((qa,qb))
    qa += Ma
    qb += Mb
a = []
b = []
c = []
for _ in range(N):
    A,B,C = map(int,input().split())
    a.append(A)
    b.append(B)
    c.append(C)
dp = [[[] for _ in range(401)] for _ in range(N+1)]
dp[0][0].append([])
for i in range(N):
    j = i+1
    for A in range(401):
        dp[j][A] = copy.deepcopy(dp[j-1][A])
        if A >= a[i]:
            for seq in dp[j-1][A-a[i]]:
                newseq = copy.deepcopy(seq)
                newseq.append(i)
                dp[j][A].append(newseq)

#後半
ans = 100000
for cand in candidates:
    A,B = cand
    for bseq in dp[N][A]:
        s = 0
        cost = 0
        for i in bseq:
            s += b[i]
            cost += c[i]
        if s == B:
            ans = min(ans,cost)
if ans != 100000:
    print(ans)
else:
    print(-1)

Submission status: Time Limit Exceeded

Solution code:
N, Ma, Mb = map(int, input().split())
D = []
atotal, btotal = 0, 0
for i in range(N):
    a, b, c = map(int, input().split())
    D.append((a, b, c))
    atotal += a
    btotal += b

Inf = 10**4
DP = [[[Inf for b in range(btotal+1)] for a in range(atotal+1)] for i in range(N+1)]
DP[0][0][0] = 0
for i in range(N):
    for a in range(atotal+1):
        for b in range(btotal+1):
            if D[i][0] + a <= atotal and D[i][1] + b <= btotal:
                DP[i+1][a + D[i][0]][b + D[i][1]] = min(DP[i+1][a + D[i][0]][b+D[i][1]], \
                    DP[i][a][b] + D[i][2])
                DP[i+1][a][b] = min(DP[i+1][a][b], DP[i][a][b])

ans = Inf
for a in range(1, atotal+1):
    for b in range(1, btotal+1):
        if a*Mb == b*Ma:
            ans = min(ans, DP[N][a][b])

print(ans if ans < Inf else -1)

Submission status: Time Limit Exceeded

Solution code:
# 入力
import sys
stdin = sys.stdin

def li(): return [int(x) for x in stdin.readline().split()]
def li_(): return [int(x)-1 for x in stdin.readline().split()]
def lf(): return [float(x) for x in stdin.readline().split()]
def ls(): return stdin.readline().split()
def ns(): return stdin.readline().rstrip()
def lc(): return list(ns())
def ni(): return int(ns())
def nf(): return float(ns())

n, ma, mb = li()
a,b,c = list(), list(), list()
for _ in range(n):
    ai,bi,ci = li()
    a.append(ai)
    b.append(bi)
    c.append(ci)
    
INF = 10**5
dp = [[[INF for _ in range(10*n+1)] for _ in range(10*n+1)] for _ in range(n+1)]
dp[0][0][0] = 0

for dr in range(n):
    for wa in range(10*n+1):
        for wb in range(10*n+1):
            dp[dr+1][wa][wb] = min(dp[dr][wa][wb], dp[dr][wa-a[dr]][wb-b[dr]] + c[dr])
            
ans = INF
k = 1
while k*ma <= 10*n and k*mb <= 10*n:
    ans = min(ans, dp[n][k*ma][k*mb])
    k += 1
    
if ans == INF:
    print(-1)
else:
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
n, ma, mb = map(int, input().split())
dp = [[[float('inf') for _ in range(401)] for _ in range(401)] for _ in range(n)]
dp[0][0][0] = 0
a0, b0, c0 = map(int, input().split())
dp[0][a0][b0] = c0

for i in range(1, n):
	dp[i][0][0] = 0
	a, b, c = map(int, input().split())
	for j in range(401):
		for k in range(401):
			if j >= a and k >= b:
				dp[i][j][k] = min(dp[i-1][j][k], dp[i-1][j-a][k-b] + c)
			else:
				dp[i][j][k] = dp[i-1][j][k]

ans = float("inf")
cnt = 400 // max(ma, mb)
for i in range(1, cnt + 1):
	ans = min(ans, dp[-1][ma * i][mb * i])

if ans <= 4000:
	print(ans)
else:
	print(-1)

Submission status: Time Limit Exceeded

Solution code:
N, Ma, Mb = map(int, input().split())
a, b, c = [], [], []
for i in range(N):
    ta, tb, tc = map(int, input().split())
    a.append(ta)
    b.append(tb)
    c.append(tc)
dp = [[[10**5 for _ in range(401)] for _ in range(401)] for _ in range(41)]
dp[0][0][0] = 0
for i in range(N):
    for j in range(401):
        for k in range(401):
            dp[i+1][j][k] = min(dp[i+1][j][k], dp[i][j][k])
            if j+a[i] < 401 and k+b[i] < 401:
                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 = 10**5
for i in range(401):
    for j in range(401):
        if i == 0 or j == 0 or Ma*j != Mb*i:
            continue
        ans = min(ans, dp[N][i][j])
        if dp[N][i][j] == 2:
            print(i, j)
if ans == 10**5:
    ans = -1
print(ans)

Submission status: Time Limit Exceeded

Solution code:
N,Ma,Mb=map(int,input().split())
a=[0 for i in range(N)]
b=[0 for i in range(N)]
c=[0 for i in range(N)]
M=401
dp=[[[10**4 for cb in range(M)]for ca in range(M)]for i in range(N+1)]
for i in range(N):
    a[i],b[i],c[i]=map(int,input().split())
dp[0][0][0]=0
for i in range(N):
    for ca in range(M):
        for cb in range(M):
            if ca+a[i]<M and cb+b[i]<M:
                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]])
            dp[i+1][ca][cb]=min([dp[i][ca][cb],dp[i+1][ca][cb]])
ans=10**4
for i in range(1,M):
    for j in range(1,M):
        if i*Mb==j*Ma:
            if dp[N][i][j]<ans:
                ans=dp[N][i][j]
if ans!=10**4:
    print(ans)
else:
    print(-1)

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
import sys
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, mul, sub

sys.setrecursionlimit(10000)


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


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


def read_float():
    return float(input())


def read_float_n():
    return list(map(float, input().split()))


def read_str():
    return input()


def read_str_n():
    return list(map(str, input().split()))


def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap


def warshall_floyd(g):
    d = defaultdict(dict)
    V = list(g.keys())
    for v in g.values():
        V.extend(list(v))
    V = set(V)
    for i in V:
        for j in V:
            if i in g and j in g[i]:
                d[i][j] = g[i][j]
            else:
                d[i][j] = sys.maxsize
    for k in g:
        for i in g:
            for j in g:
                if d[i][j] > d[i][k] + d[k][j]:
                    d[i][j] = d[i][k] + d[k][j]

    return d


@mt
def slv(N, MA, MB, ABC):
    MAB = MA/MB

    @lru_cache(maxsize=None)
    def f(pick, a, b, c):
        if a != 0 and b != 0:
            if a*MB == b*MA:
                return c
        ans = sys.maxsize
        ab = 1 if b == 0 else a/b
        for i, (a_, b_, c_) in enumerate(ABC):
            m = (1 << i)
            if pick & m == 0:
                ab_ = a_ / b_
                if ab < MAB and ab_ < 1:
                    continue
                if ab > MAB and ab_ > 1:
                    continue
                ans = min(ans, f(pick | m, a+a_, b+b_, c+c_))

        return ans
    ans = f(0, 0, 0, 0)
    return -1 if ans == sys.maxsize else ans


def main():
    N, MA, MB = read_int_n()
    ABC = [read_int_n() for _ in range(N)]

    print(slv(N, MA, MB, ABC))


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
import sys
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, mul, sub

sys.setrecursionlimit(10000)


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


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


def read_float():
    return float(input())


def read_float_n():
    return list(map(float, input().split()))


def read_str():
    return input()


def read_str_n():
    return list(map(str, input().split()))


def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap


def warshall_floyd(g):
    d = defaultdict(dict)
    V = list(g.keys())
    for v in g.values():
        V.extend(list(v))
    V = set(V)
    for i in V:
        for j in V:
            if i in g and j in g[i]:
                d[i][j] = g[i][j]
            else:
                d[i][j] = sys.maxsize
    for k in g:
        for i in g:
            for j in g:
                if d[i][j] > d[i][k] + d[k][j]:
                    d[i][j] = d[i][k] + d[k][j]

    return d


@mt
def slv(N, MA, MB, ABC):
    MAB = MA/MB

    @lru_cache(maxsize=None)
    def f(pick, a, b, c):
        if a != 0 and b != 0:
            if a == (b*MA)//MB and (b*MA) % MB == 0:
                return c
        ans = sys.maxsize
        ab = 1 if b == 0 else a/b
        for i, (a_, b_, c_) in enumerate(ABC):
            m = (1 << i)
            if pick & m == 0:
                ab_ = a_ / b_
                if ab < MAB and ab_ < 1:
                    continue
                if ab > MAB and ab_ > 1:
                    continue
                ans = min(ans, f(pick | m, a+a_, b+b_, c+c_))

        return ans
    ans = f(0, 0, 0, 0)
    return -1 if ans == sys.maxsize else ans


def main():
    N, MA, MB = read_int_n()
    ABC = [read_int_n() for _ in range(N)]

    print(slv(N, MA, MB, ABC))


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
import sys
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, mul, sub

sys.setrecursionlimit(10000)


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


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


def read_float():
    return float(input())


def read_float_n():
    return list(map(float, input().split()))


def read_str():
    return input()


def read_str_n():
    return list(map(str, input().split()))


def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap


def warshall_floyd(g):
    d = defaultdict(dict)
    V = list(g.keys())
    for v in g.values():
        V.extend(list(v))
    V = set(V)
    for i in V:
        for j in V:
            if i in g and j in g[i]:
                d[i][j] = g[i][j]
            else:
                d[i][j] = sys.maxsize
    for k in g:
        for i in g:
            for j in g:
                if d[i][j] > d[i][k] + d[k][j]:
                    d[i][j] = d[i][k] + d[k][j]

    return d


@mt
def slv(N, MA, MB, ABC):

    @lru_cache(maxsize=None)
    def f(pick, a, b, c):
        if a != 0 and b != 0:
            if a == (b*MA)//MB and (b*MA) % MB == 0:
                return c
        ans = sys.maxsize
        for i, (a_, b_, c_) in enumerate(ABC):
            m = (1 << i)
            if pick & m == 0:
                ans = min(ans, f(pick | m, a+a_, b+b_, c+c_))

        return ans
    ans = f(0, 0, 0, 0)
    return -1 if ans == sys.maxsize else ans


def main():
    N, MA, MB = read_int_n()
    ABC = [read_int_n() for _ in range(N)]

    print(slv(N, MA, MB, ABC))


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
n, ma, mb = map(int, input().split())
INF = 100001
dp = [[[INF for k in range(401)] for j in range(401)] for i in range(n+1)]
a, b, c = [0 for i in range(n)], [0 for i in range(n)], [0 for i in range(n)]


def solve():
    for i in range(n+1):
        dp[i][0][0] = 0

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

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

    return min_cost


def main():
    for i in range(n):
        aa, bb, cc = map(int, input().split())
        a[i], b[i], c[i] = aa, bb, cc

    cost = solve()

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


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
n, ma, mb = map(int, input().split())
INF = 100001
dp = [[[INF for k in range(401)] for j in range(401)] for i in range(n+1)]
a, b, c = [0 for i in range(n)], [0 for i in range(n)], [0 for i in range(n)]


def solve():
    for i in range(n+1):
        dp[i][0][0] = 0

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

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

    return min_cost


def main():
    for i in range(n):
        aa, bb, cc = map(int, input().split())
        a[i], b[i], c[i] = aa, bb, cc

    cost = solve()

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


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
from functools import reduce

N, Ma, Mb = map(int, input().split())
X = np.array([list(map(int, input().split())) for _ in range(N)])
z = [4001]

def update_z(_y, index2):
    tmp = reduce(lambda a,b:a+b, [x for k,x in enumerate(X) if k in index2])
    if tmp[0]*Mb == tmp[1]*Ma:
        z.append(min(_y, tmp[2]))

def rec(y=4001, i=0, index=None):
    if i<N:
        if index:
            for j in range(i,N):
                update_z(y, index+[j])
                rec(y, j+1, index + [j])
        else:
            for j in range(i,N):
                update_z(y, [j])
                rec(y, j+1, [j])

rec()
print(-1 if min(z)>4000 else min(z))

Submission status: Time Limit Exceeded

Solution code:
from itertools import combinations
N, Ma, Mb = list(map(int, input().split()))
abc = [list(map(int, input().split())) for _ in range(N)]
min_cost = -1
for _i in range(1, N+1):
    all_pattern = list(combinations(range(N), _i))
    for _j in all_pattern:
        _a = sum([abc[_k][0] for _k in _j])
        _b = sum([abc[_k][1] for _k in _j])
        _c = sum([abc[_k][2] for _k in _j])
        if _b * Ma == _a * Mb:
            if min_cost == -1 or min_cost > _c:
                min_cost = _c
print(min_cost)

Submission status: Time Limit Exceeded

Solution code:
n, ma, mb = map(int, input().split())
INF = 100001
dp = [[[INF for k in range(401)] for j in range(401)] for i in range(n+1)]
a, b, c = [0 for i in range(n)], [0 for i in range(n)], [0 for i in range(n)]


def solve():
    dp[0][0][0] = 0

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

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

    return min_cost


def main():
    for i in range(n):
        aa, bb, cc = map(int, input().split())
        a[i], b[i], c[i] = aa, bb, cc

    cost = solve()

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


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
N, Ma, Mb = map(int, input().split(' '))
Chems = [list(map(int, input().split(' '))) for _ in range(N)]
dp = [[[float('INF') for i in range(401)] for j in range(401)] for k in range(N+1)]
dp[0][0][0] = 0

for i,(a, b, c) in enumerate(Chems):
    for ca in range(401):
        for cb in range(401):
            dp[i+1][ca][cb] = min(dp[i+1][ca][cb], dp[i][ca][cb])
            if ca + a <= 400 and cb + b <= 400:
                dp[i+1][ca + a][cb + b] = min(dp[i+1][ca + a][cb + b], dp[i][ca][cb] + c)
res = float('INF')
for (a, b) in zip(range(401), range(401)):
    if a != 0 and b != 0 and a * Mb == b * Ma:
        res = min(res, dp[N][a][b])
if res == float('INF'): res = -1
print(res)

Submission status: Time Limit Exceeded

Solution code:
from copy import deepcopy
N, Ma, Mb = map(int, input().split())
L = [[float("inf")]*410 for i in range(410)]
P = [[0, 0]]
L[0][0] = 0

for i in range(N):
    a, b, c = map(int, input().split())
    OldP = P.copy()
    OldL = deepcopy(L)
    for p in OldP:
        if L[p[0]+a][p[1]+b] == float("inf"):
            P.append([p[0]+a, p[1]+b])
        L[p[0]+a][p[1]+b] = min(OldL[p[0]+a][p[1]+b], OldL[p[0]][p[1]]+c)
g = [Ma, Mb]
ans = float("inf")
while g[0]<410 and g[1]<410:
    ans = min(ans, L[g[0]][g[1]])
    g[0] += Ma
    g[1] += Mb
print(ans if ans != float("inf") else -1)

Submission status: Time Limit Exceeded

Solution code:
N,M,K=map(int,input().split())
table=[]
for i in range(N):
    a,b,c=map(int,input().split())
    table.append([a,b,c])

inf=10**9
#[N+1][400a][400b]
dp=[[[inf]*401 for i in range(401)]for i in range(N+1)]
dp[0][0][0]=0
for i in range(1,N+1):
    a,b,c = table[i-1]
    for j in range(401):
        for k in range(401):
            dp[i][j][k]=dp[i-1][j][k]
            if 400>=j-a>=0 and 400>=k-b>=0:
                dp[i][j][k] =min(dp[i-1][j][k],dp[i-1][j-a][k-b]+c)

ans =10**9
i=1
while max(M,K)*i <401:
    ans = min(ans,dp[N][M*i][K*i])
    i=i+1
if ans ==10**9:
    print(-1)
else:
    print(ans)