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 math
from itertools import chain, combinations

def powerset(iterable):
    """ powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3) """
    s = list(iterable)
    return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))


data = []
part = []
cost = math.inf
n = input()
n = n.split()
N = int(n[0])
Ma = int(n[1])
Mb = int(n[2])
for i in range(N):
    part.append(i)
    tmp = input()
    tmp = tmp.split()
    tmp = list(map(int, tmp))
    data.append(tmp)
part = powerset(part)
for i in part:
    a = 0
    b = 0
    c = 0
    for j in i:
        a += data[j][0]
        b += data[j][1]
        c += data[j][2]
    if (Ma*b == Mb*a) and cost > c and (c > 0):
        cost = c
if cost == math.inf:
    print('-1')
else:
    print(cost)

Submission status: Time Limit Exceeded

Solution code:
k, a, b = map(int, input().split()) 
item = [list(map(int, input().split())) for i in range(k)]
n = len(item)
cost_list = []
for i in range(2 ** n):
    bag = []
    for j in range(n):  # このループが一番のポイント
        if ((i >> j) & 1):  # 順に右にシフトさせ最下位bitのチェックを行う
            bag.append(item[j])  # フラグが立っていたら bag に果物を詰める

    drag_a = 0
    drag_b = 0
    cost = 0
    for var in bag:
        drag_a += var[0]
        drag_b += var[1]
        cost += var[2]
    if drag_a*b == drag_b*a:
        cost_list.append(cost)
cost_list.remove(0)
if cost_list == []:
    print('-1')
else:    
    print(min(cost_list))

Submission status: Time Limit Exceeded

Solution code:
import sys
n, ma, mb = map(int,input().split())
#s = sys.stdin.readiline().rstrip()
medicine = [list(map(int,input().split())) for i in range(n)]
money = float('inf')
#oneorzero = [[] for i in range(n)]

def dec2bin(target):
    amari = [[] for i in range(2 ** target)]
    for j in range(2 ** target):
        kazu = j
        while kazu != 0:
            amari[j].append(kazu % 2)
            kazu = kazu // 2
    for j in range(2 ** target):
        while len(amari[j]) < target:
            amari[j].append(0)
        amari[j].reverse()

    return amari

oneorzero = dec2bin(n)

for i in range(len(oneorzero)):
    Asum = 0
    Bsum = 0
    Csum = 0
    for j in range(n):
        if oneorzero[i][j] == 1:
            Asum += medicine[j][0]
            Bsum += medicine[j][1]
            Csum += medicine[j][2]
    if Bsum * ma == Asum * mb and 0 < Csum < money:
        money = Csum
        

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

Submission status: Time Limit Exceeded

Solution code:
N, Ma, Mb = map(int, input().split())
data = []
pool = []

for i in range(N):
  data.append(tuple(map(int, input().split())))
  
prices = set()
count = 0

for i in range(2** N- 1):
  count+= 1
  strbinc = str(bin(count))[2:].zfill(N)
  listbinc = list(strbinc)
  C = listbinc.count("1")
  
  memory = set()
  
  for k in range(C):
    index = listbinc.index("1")
    listbinc[index] = "0"
    memory.add(index)
    
  flag = 0 
 
  for memories in pool:
      if(memory > memories):
        flag = 1
        break  
  
  if(flag == 0):
    total_a = 0
    total_b = 0
    total_price = 0
    for j in range(N):
      total_a+= int(strbinc[j])* data[j][0]
      total_b+= int(strbinc[j])* data[j][1]
      total_price+= int(strbinc[j])* data[j][2]
    if(total_a* Mb == total_b* Ma):
      pool.append(memory)
      prices.add(total_price)
     
    
try:
  print(min(prices))
except:
  print(-1)

Submission status: Time Limit Exceeded

Solution code:
def twodevider(n):
  while n% 2 == 0:
    n/= 2
  if(n == 1):
    return True
  else:
    return False

N, Ma, Mb = map(int, input().split())
data = []
pool = []

for i in range(N):
  data.append(tuple(map(int, input().split())))
  
prices = set()
count = 0

for i in range(2** N- 1):
  count+= 1
  strbinc = str(bin(count))[2:].zfill(N)
  listbinc = list(strbinc)
  C = listbinc.count("1")
  
  memory = set()
  
  for k in range(C):
    index = listbinc.index("1")
    listbinc[index] = "0"
    memory.add(index)
    
    total_a = 0
    total_b = 0
    total_price = 0
    for j in range(N):
      total_a+= int(strbinc[j])* data[j][0]
      total_b+= int(strbinc[j])* data[j][1]
      total_price+= int(strbinc[j])* data[j][2]
    if(total_a* Mb == total_b* Ma):
      
      flag = 0
      
      for memories in pool:
        if(memory > memories):
          flag = 1
          break
      if(flag == 0):
        pool.append(memory)
        prices.add(total_price)
    
try:
  print(min(prices))
except:
  print(-1)

Submission status: Time Limit Exceeded

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

for i in range(N):
  data.append(tuple(map(int, input().split())))
  
prices = set()
count = 0

for i in range(2** N- 1):
  count+= 1
  strbinc = str(bin(count))[2:].zfill(N)
  total_a = 0
  total_b = 0
  total_price = 0
  for j in range(N):
    total_a+= int(strbinc[j])* data[j][0]
    total_b+= int(strbinc[j])* data[j][1]
    total_price+= int(strbinc[j])* data[j][2]
  if(total_a* Mb == total_b* Ma):
    prices.add(total_price)
    
try:
  print(min(prices))
except:
  print(-1)

Submission status: Time Limit Exceeded

Solution code:
INF = 10 ** 5
N, Ma, Mb = map(int,input().split())
dp = [[[INF for i in range(10 * N + 1)] for j in range(10 * N + 1)] for k 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(10 * N + 1):
        for k in range(10 * N + 1):
            dp[i+1][j][k] = min(dp[i][j][k], dp[i+1][j][k])
            if j + a <= 10 * N and k + b <= 10 * N:
                dp[i+1][j+a][k+b] = min(dp[i][j][k] + c, dp[i+1][j+a][k+b])

ans = INF
i = 1
while Ma * i <= 10 * N and Mb * i <= 10 * N:
    ans = min(ans, dp[N][Ma*i][Mb*i])
    i += 1

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

Submission status: Time Limit Exceeded

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

    INF = 10**18
    dp = [[[INF]*405 for i in range(405)] for j in range(n+1)]
    dp[0][0][0] = 0
    for i in range(n):
        a, b, c = ABC[i]
        for j in range(405):
            for k in range(405):
                dp[i+1][j][k] = min(dp[i+1][j][k], dp[i][j][k])
                nj, nk = j+a, k+b
                if 1 <= nj <= 404 and 1 <= nk <= 404:
                    dp[i+1][nj][nk] = min(dp[i][nj][nk], dp[i][j][k]+c)

    import fractions
    ans = INF
    for j in range(1, 405):
        for k in range(1, 405):
            if ma*k == mb*j:
                ans = min(ans, dp[n][j][k])
    if ans == INF:
        print(-1)
    else:
        print(ans)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import math
#import numpy as np
import queue
from collections import deque,defaultdict
import heapq as hpq
from sys import stdin,setrecursionlimit
#from scipy.sparse.csgraph import dijkstra
#from scipy.sparse import csr_matrix
ipt = stdin.readline
setrecursionlimit(10**7)

def main():
    n,ma,mb = map(int,ipt().split())
    mds = [list(map(int,ipt().split())) for i in [0]*n]
    fmt = "0"+str(n)+"b"
    mi = 10**18
    for i in range(2**n):
        li = list(map(int,format(i,fmt)))
        sa = 0
        sb = 0
        cst = 0
        for i,lii in enumerate(li):
            if lii == 1:
                sa += mds[i][0]
                sb += mds[i][1]
                cst += mds[i][2]
        if sa*mb == sb*ma > 0 and mi > cst:
            mi = cst

    if mi == 10**18:
        print(-1)
    else:
        print(mi)

    return

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
N, Ma, Mb = map(int, input().split())
abc = [list(map(int, input().split())) for i in range(N)]
INF = 10**5
n = 10*N + 1
dp = [[[INF]*n for i in range(n)] for j in range(N+1)]
dp[0][0][0] = 0

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

ans = INF
dp[-1][0][0] = INF
for j in range(n):
  for k in range(n):
    if j * Mb == k*Ma:
      ans = min(ans, dp[-1][j][k])

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

Submission status: Time Limit Exceeded

Solution code:
import sys
import itertools
input = sys.stdin.readline
 
def I(): return int(input())
def MI(): return map(int, input().split())
def LI(): return list(map(int, input().split()))


def main():
    n, ma, mb =  MI()
    num = ma / mb
    buy = [i for i in range(n)]
    mylist = [LI() for i in range(n)]
    result = []
    
    for j in range(1,len(buy)+1):
        for conb in itertools.combinations(buy, j):
            tempa = 0
            tempb = 0
            price = 0
            for i in conb:
                tempa += mylist[i][0]
                tempb += mylist[i][1]
                price += mylist[i][2]
            if tempa/tempb == num:
                result.append(price)
                
    if len(result) == 0:
        print(-1)
    else:
        print(min(result))


main()

Submission status: Time Limit Exceeded

Solution code:
import sys
import itertools
input = sys.stdin.readline
 
def I(): return int(input())
def MI(): return map(int, input().split())
def LI(): return list(map(int, input().split()))


def main():
    n, ma, mb =  MI()
    num = ma / mb
    buy = [i for i in range(n)]
    mylist = [LI() for i in range(n)]
    result = []
    
    for j in range(1,len(buy)+1):
        for conb in itertools.combinations(buy, j):
            tempa = 0
            tempb = 0
            price = 0
            for i in conb:
                tempa += mylist[i][0]
                tempb += mylist[i][1]
                price += mylist[i][2]
            if tempa/tempb == num:
                result.append(price)
                
    if len(result) == 0:
        print(-1)
    else:
        print(min(result))


main()

Submission status: Time Limit Exceeded

Solution code:
import sys,queue,math,copy,itertools,bisect,collections,heapq

def main():
    INF = 10**5
    LI = lambda : [int(x) for x in sys.stdin.readline().split()]

    n,ma,mb = LI()
    med = [LI() for _ in range(n)]
    h1 = []
    h2 = []

    for i in range(2 ** (n//2)):
        bit = 1
        ta = 0
        tb = 0
        tc = 0
        for j in range(n//2):
            if i & bit:
                a,b,c = med[j]
                ta += a
                tb += b
                tc += c
            bit <<= 1
        dif = ta * mb - tb * ma
        h1.append((dif,tc))

    for i in range(2 ** (n - n//2)):
        bit = 1
        ta = 0
        tb = 0
        tc = 0
        for j in range(n - n//2):
            if i & bit:
                a,b,c = med[j+n//2]
                ta += a
                tb += b
                tc += c
            bit <<= 1
        dif = tb * ma - ta * mb
        h2.append((dif,tc))

    h1.sort()
    h2.sort()
    i = 0
    ans = INF
    for h,c in h1:
        while h2[i][0] < h:
            i += 1
            if i >= len(h2): break
        else:
            k = i
            while h2[k][0] == h:
                if c != 0 or h2[k][1] != 0:
                    ans = min(ans,c+h2[k][1])
                k += 1
                if k >= len(h2): break

        if i >= len(h2): break
    if ans < INF:
        print(ans)
    else:
        print(-1)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
MX = 401

N, Ma, Mb = map(int, input().split())
A = [0]*N
B = [0]*N
C = [0]*N
for i in range(N):
    a, b, c = map(int, input().split())
    A[i] = a
    B[i] = b
    C[i] = c
INF = 10**18
dp = [[[INF]*MX for i in range(MX)] for i in range(N+1)]
dp[0][0][0] = 0
for i in range(1, N+1):
    for j in range(0, MX):
        for k in range(0, MX):
            dp[i][j][k] = dp[i-1][j][k]
            if j < A[i-1] or k < B[i-1]: continue
            dp[i][j][k] = min(dp[i][j][k], dp[i-1][j-A[i-1]][k-B[i-1]]+C[i-1])
ans = INF
for i in range(1, MX):
    if Ma*i > MX-1 or Mb*i > MX-1: break
    ans = min(ans, dp[N][Ma*i][Mb*i])
if ans == INF:
    print(-1)
else:
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
n,ma,mb = map(int,input().split())

INF = 10**4
dp = [[[INF] * (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 = map(int,input().split())
    for ai in range(n*10):
        for bi in range(n*10):
            if ai>=a and bi>=b:
                tmp = dp[i][ai-a][bi-b] + c
            else:
                tmp = INF
            dp[i+1][ai][bi] = min(dp[i][ai][bi], tmp)

ans = min(dp[n][ma*i][mb*i] for i in range(1,n*10//max(ma,mb)+1) )
if ans == INF: ans = -1
    
print(ans)

Submission status: Time Limit Exceeded

Solution code:
def half_enumeration(a, *, func):
    """正しい英訳は不明"""
    n = len(a)
    h = n // 2

    def enum(h, *, second_half: bool = False):
        p = set()
        if second_half:
            b = a[h:]
        else:
            b = a[:h]

        for x in b:
            q = set()
            for e in p:
                q.add(func(e, x))
            p.add(x)
            p.update(q)
        return p

    return enum(h), enum(h, second_half=True)


def main():
    from itertools import chain
    from operator import add

    INF = 40 * 100 + 1

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

    def update(e, x):
        return e[0] + x[0], e[1] + x[1]

    xcs = []
    for _ in range(N):
        ai, bi, ci = map(int, input().split())
        x = Ma * bi - Mb * ai  # Σai:Σbi=Ma:Mb<->Ma*Σbi-Mb*Σai=0
        xcs.append((x, ci))

    p1, p2 = half_enumeration(xcs, func=update)

    ans = INF
    for x, c in chain(p1, p2):
        if x == 0 and ans > c:
            ans = c
    for x1, c1 in p1:
        for x2, c2 in p2:
            if x1 + x2 == 0 and ans > c1 + c2:
                ans = c1 + c2
    print(-1 if ans == INF else ans)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
def half_enumeration(a, *, func):
    """正しい英訳は不明"""
    n = len(a)
    h = n // 2

    def enum(h, *, second_half: bool = False):
        p = set()
        if second_half:
            b = a[h:]
        else:
            b = a[:h]

        for x in b:
            q = set()
            for e in p:
                q.add(func(e, x))
            p.add(x)
            p.update(q)
        return p

    return enum(h), enum(h, second_half=True)


def main():
    from itertools import chain, starmap
    from operator import add

    INF = 40 * 100 + 1

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

    def update(e, x):
        return tuple(starmap(add, zip(e, x)))

    xcs = []
    for _ in range(N):
        ai, bi, ci = map(int, input().split())
        x = Ma * bi - Mb * ai  # Σai:Σbi=Ma:Mb<->Ma*Σbi-Mb*Σai=0
        xcs.append((x, ci))

    p1, p2 = half_enumeration(xcs, func=update)

    ans = INF
    for x, c in chain(p1, p2):
        if x == 0 and ans > c:
            ans = c
    for x1, c1 in p1:
        for x2, c2 in p2:
            if x1 + x2 == 0 and ans > c1 + c2:
                ans = c1 + c2
    print(-1 if ans == INF else ans)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
def main():
    inf = 100 * 40 + 1
    mx = 400

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

    dp = [[[inf] * (400 + 1) for _ in range(400 + 1)] for _ in range(N + 1)]
    dp[0][0][0] = 0
    for i in range(N):
        ai, bi, ci = map(int, input().split())
        for a in range(mx + 1):
            for b in range(mx + 1):
                dp[i + 1][a][b] = dp[i][a][b]
        for a in range(ai, mx + 1):
            for b in range(bi, mx + 1):
                dp[i + 1][a][b] = min(
                    dp[i + 1][a][b],
                    dp[i][a - ai][b - bi] + ci
                )
    k = 1
    ans = inf
    while Ma * k <= mx and Mb * k <= mx:
        ans = min(ans, dp[N][Ma * k][Mb * k])
        k += 1

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


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
import math
from collections import defaultdict
from bisect import bisect_left, bisect_right

sys.setrecursionlimit(10**7)
def input():
    return sys.stdin.readline()[:-1]

mod = 10**9 + 7

def I(): return int(input())
def LI(): return list(map(int, input().split()))
def LIR(row,col):
    if row <= 0:
        return [[] for _ in range(col)]
    elif col == 1:
        return [I() for _ in range(row)]
    else:
        read_all = [LI() for _ in range(row)]
        return map(list, zip(*read_all))

#################

from itertools import product

N,Ma,Mb = LI()
a,b,c = LIR(N,3)

Z1 = list(product([0,1],repeat=N//2))
Z2 = list(product([0,1],repeat=N-N//2))

d1 = defaultdict(lambda:5000)
d2 = defaultdict(lambda:5000)

for z in Z1:
    val_a = 0
    val_b = 0
    cost = 0
    for i,z0 in enumerate(z):
        if z0:
            val_a += a[i]
            val_b += b[i]
            cost += c[i]
    if cost < d1[(val_a,val_b)]:
        d1[(val_a,val_b)] = cost

for z in Z2:
    val_a = 0
    val_b = 0
    cost = 0
    for i,z0 in enumerate(z):
        if z0:
            val_a += a[N//2+i]
            val_b += b[N//2+i]
            cost += c[N//2+i]
    if cost < d2[(val_a,val_b)]:
        d2[(val_a,val_b)] = cost

vals = []
now = 1
while True:
    if Ma*now <= sum(a) and Mb*now <= sum(b):
        vals.append((Ma*now,Mb*now))
        now += 1
    else:
        break

ans = 5000
for k in d1.keys():
    for v in vals[::-1]:
        left_a = v[0]-k[0]
        left_b = v[1]-k[1]
        if left_a < 0 or left_b < 0:
            break
        if d1[k]+d2[(left_a,left_b)] < ans:
            ans = d1[k]+d2[(left_a,left_b)]

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

Submission status: Time Limit Exceeded

Solution code:
import sys
import math
from collections import defaultdict
from bisect import bisect_left, bisect_right

sys.setrecursionlimit(10**7)
def input():
    return sys.stdin.readline()[:-1]

mod = 10**9 + 7

def I(): return int(input())
def LI(): return list(map(int, input().split()))
def LIR(row,col):
    if row <= 0:
        return [[] for _ in range(col)]
    elif col == 1:
        return [I() for _ in range(row)]
    else:
        read_all = [LI() for _ in range(row)]
        return map(list, zip(*read_all))

#################

from itertools import product

N,Ma,Mb = LI()
a,b,c = LIR(N,3)

n = N//2
Z1 = list(product([0,1],repeat=n))
Z2 = list(product([0,1],repeat=N-n))

d1 = defaultdict(list)
d2 = defaultdict(list)

for bit in range(1<<n):
    L = bit.bit_length()
    val_a = 0
    val_b = 0
    cost = 0
    for i in range(L):
        if bit>>i&1:
            val_a += a[n-1-i]
            val_b += b[n-1-i]
            cost += c[n-1-i]
    d1[(val_a,val_b)].append(cost)

for k in d1.keys():
    d1[k].sort()

for bit in range(1<<(N-n)):
    L = bit.bit_length()
    val_a = 0
    val_b = 0
    cost = 0
    for i in range(L):
        if bit>>i&1:
            val_a += a[N-1-i]
            val_b += b[N-1-i]
            cost += c[N-1-i]
    d2[(val_a,val_b)].append(cost)

for k in d2.keys():
    d2[k].sort()

vals = []
now = 1
while True:
    if Ma*now <= sum(a) and Mb*now <= sum(b):
        vals.append((Ma*now,Mb*now))
        now += 1
    else:
        break

ans = float('inf')
for v in vals:
    for k in d1.keys():
        left_a = v[0]-k[0]
        left_b = v[1]-k[1]
        if d2[(left_a,left_b)]:
            if d1[k][0]+d2[(left_a,left_b)][0] < ans:
                ans = d1[k][0]+d2[(left_a,left_b)][0]

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

Submission status: Time Limit Exceeded

Solution code:
import sys
import math
from collections import defaultdict
from bisect import bisect_left, bisect_right

sys.setrecursionlimit(10**7)
def input():
    return sys.stdin.readline()[:-1]

mod = 10**9 + 7

def I(): return int(input())
def LI(): return list(map(int, input().split()))
def LIR(row,col):
    if row <= 0:
        return [[] for _ in range(col)]
    elif col == 1:
        return [I() for _ in range(row)]
    else:
        read_all = [LI() for _ in range(row)]
        return map(list, zip(*read_all))

#################

# Ma:Mbを満たす量を全探索する
# 量を決めたときの最小予算は半分全列挙から分かる

from itertools import product

N,Ma,Mb = LI()
a,b,c = LIR(N,3)

Z1 = list(product([0,1],repeat=N//2))
Z2 = list(product([0,1],repeat=N-N//2))

d1 = defaultdict(list)
d2 = defaultdict(list)

for z in Z1:
    val_a = 0
    val_b = 0
    cost = 0
    for i,z0 in enumerate(z):
        if z0:
            val_a += a[i]
            val_b += b[i]
            cost += c[i]
    d1[(val_a,val_b)].append(cost)

for k in d1.keys():
    d1[k].sort()

for z in Z2:
    val_a = 0
    val_b = 0
    cost = 0
    for i,z0 in enumerate(z):
        if z0:
            val_a += a[N//2+i]
            val_b += b[N//2+i]
            cost += c[N//2+i]
    d2[(val_a,val_b)].append(cost)

for k in d2.keys():
    d2[k].sort()

vals = []
now = 1
while True:
    if Ma*now <= sum(a) and Mb*now <= sum(b):
        vals.append((Ma*now,Mb*now))
        now += 1
    else:
        break

ans = float('inf')
for v in vals:
    for k in d1.keys():
        left_a = v[0]-k[0]
        left_b = v[1]-k[1]
        if d2[(left_a,left_b)]:
            if d1[k][0]+d2[(left_a,left_b)][0] < ans:
                ans = d1[k][0]+d2[(left_a,left_b)][0]

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

Submission status: Time Limit Exceeded

Solution code:
import sys
import math
from collections import defaultdict
from bisect import bisect_left, bisect_right

sys.setrecursionlimit(10**7)
def input():
    return sys.stdin.readline()[:-1]

mod = 10**9 + 7

def I(): return int(input())
def LI(): return list(map(int, input().split()))
def LIR(row,col):
    if row <= 0:
        return [[] for _ in range(col)]
    elif col == 1:
        return [I() for _ in range(row)]
    else:
        read_all = [LI() for _ in range(row)]
        return map(list, zip(*read_all))

#################

# Ma:Mbを満たす量を全探索する
# 量を決めたときの最小予算は半分全列挙から分かる

from itertools import product

N,Ma,Mb = LI()
a,b,c = LIR(N,3)

Z1 = list(product([0,1],repeat=N//2))
Z2 = list(product([0,1],repeat=N-N//2))

d1 = defaultdict(list)
d2 = defaultdict(list)

for z in Z1:
    val_a = 0
    val_b = 0
    cost = 0
    for i,z0 in enumerate(z):
        if z0:
            val_a += a[i]
            val_b += b[i]
            cost += c[i]
    d1[(val_a,val_b)].append(cost)

for k in d1.keys():
    d1[k].sort()

for z in Z2:
    val_a = 0
    val_b = 0
    cost = 0
    for i,z0 in enumerate(z):
        if z0:
            val_a += a[N//2+i]
            val_b += b[N//2+i]
            cost += c[N//2+i]
    d2[(val_a,val_b)].append(cost)

for k in d2.keys():
    d2[k].sort()

vals = []
now = 1
while True:
    if max(Ma*now,Mb*now) <= 10*N:
        vals.append((Ma*now,Mb*now))
        now += 1
    else:
        break

ans = float('inf')
for v in vals:
    for k in d1.keys():
        left_a = v[0]-k[0]
        left_b = v[1]-k[1]
        if d2[(left_a,left_b)]:
            if d1[k][0]+d2[(left_a,left_b)][0] < ans:
                ans = d1[k][0]+d2[(left_a,left_b)][0]

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

Submission status: Time Limit Exceeded

Solution code:
import sys
import heapq, math
from itertools import zip_longest, permutations, combinations, combinations_with_replacement
from itertools import accumulate, dropwhile, takewhile, groupby
from functools import lru_cache
from copy import deepcopy

N, Ma, Mb = map(int, input().split())
A = [0] * N
B = [0] * N
C = [0] * N

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

INF = 1 << 50
LEN = 500
dp = [[INF] * (LEN + 1) for _ in range(LEN + 1)]
dp[0][0] = 0

for i in range(N):
    for j in range(LEN, A[i] - 1, -1):
        for k in range(LEN, B[i] - 1, -1):
            dp[j][k] = min(dp[j][k], dp[j - A[i]][k - B[i]] + C[i])

cnt = 1
ans = INF
while cnt * Ma < LEN and cnt * Mb < LEN:
    ans = min(ans, dp[cnt * Ma][cnt * Mb])
    cnt += 1

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

Submission status: Time Limit Exceeded

Solution code:
MOD = 10 ** 9 + 7
INF = 10  ** 7
def main():
    n,a,b = map(int,input().split())
    m = n//2
    Chemical = [tuple(map(int,input().split())) for _ in range(n)]
    Chemical1 = Chemical[:m]
    Chemical2 = Chemical[m:]
    Sum1 = [[INF] * 405 for _ in range(405)]
    Sum2 = [[INF] * 405 for _ in range(405)]
    for bit in range(1<<m):
        cost,v1,v2 = 0,0,0
        for i in range(m):
            if (bit>>i)&1:
                d,e,f = Chemical1[i]
                v1 += d
                v2 += e
                cost += f
        Sum1[v1][v2] = min(Sum1[v1][v2],cost)
    
    for bit in range(1<<(n - m)):
        cost,v1,v2 = 0,0,0
        for i in range(n - m):
            if (bit>>i)&1:
                d,e,f = Chemical2[i]
                v1 += d
                v2 += e
                cost += f
        Sum2[v1][v2] = min(Sum2[v1][v2],cost)
    
    ans = INF
    for i in range(405):
        for j in range(405):
            if Sum1[i][j] != INF:
                C = Sum1[i][j]
                k = max((i + a - 1)//a,(j + b - 1)//b,1)
                while k * a - i < 405 and k*b - j < 405:
                    if Sum2[k*a - i][k*b - j] != INF:
                        ans = min(ans,Sum2[k*a - i][k*b - j] + C)
                    k += 1
    print(ans if ans != INF else -1)
if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

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

INF = float('inf')

dp = [[INF for b in range(401)] for a in range(401)]

dp[0][0] = 0

for i in range(1,N+1):
    ai,bi,ci = map(int,input().split())
    for a in range(400,-1,-1):
        for b in range(400,-1,-1):
            if a-ai >= 0 and b-bi >= 0:
                dp[a][b] = min(dp[a][b],dp[a-ai][b-bi]+ci)


ans = INF
for j in range(1,401):
    if Ma*j > 400 or Mb*j > 400:
        break
    ans = min(ans,dp[Ma*j][Mb*j])
print(ans if ans != INF else -1)

Submission status: Time Limit Exceeded

Solution code:
from itertools import product
N, A, B = map(int, input().split())

C = [tuple(map(int, input().split())) for n in range(N)]

ans = 4001
for D in product((True, False), repeat=N):
    E = 0
    F = 0
    G = 0
    for n in range(N):
        if D[n]:
            E += C[n][0]
            F += C[n][1]
            G += C[n][2]

    if E != 0 and F / E == B / A:
        ans = min(ans, G)

if ans == 4001:
    print(-1)

else:
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
from itertools import product
N, A, B = map(int, input().split())

C = {n:tuple(map(int, input().split())) for n in range(N)}

ans = 4001
for D in product((True, False), repeat=N):
    E = [0, 0, 0]
    for n in range(N):
        if D[n]:
            E[0] += C[n][0]
            E[1] += C[n][1]
            E[2] += C[n][2]

    if E[0] != 0 and E[1] / E[0] == B / A:
        ans = min(ans, E[2])

if ans == 4001:
    print(-1)

else:
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
from itertools import product
N, A, B = map(int, input().split())

C = [tuple(map(int, input().split())) for n in range(N)]

ans = 4001
for D in product((True, False), repeat=N):
    E = [0, 0, 0]
    for n in range(N):
        if D[n]:
            E[0] += C[n][0]
            E[1] += C[n][1]
            E[2] += C[n][2]

    if E[0] != 0 and E[1] / E[0] == B / A:
        ans = min(ans, E[2])

if ans == 4001:
    print(-1)

else:
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
N,Ma,Mb=map(int,input().split())
a=[0 for k in range(N)]
b=[0 for k in range(N)]
c=[0 for k in range(N)]
import copy
for k in range(N):
    a[k],b[k],c[k]=map(int,input().split())
Sa=sum(a)
Sb=sum(b)
dp =[[5000 for k in range(Sb+1)]for k in range(Sa+1)]
dp[0][0]=0
for k in range(N):
    listj=[]
    listl=[]
    co=copy.deepcopy(dp)
    for j in range(Sa-a[k]+1):
        for l in range(Sb-b[k]+1):
            if dp[j][l]!=5000:
                listj.append(j)
                listl.append(l)
    for m in range(len(listl)):
        dp[listj[m]+a[k]][listl[m]+b[k]]=min(co[listj[m]][listl[m]]+c[k], co[listj[m]+a[k]][listl[m]+b[k]])
ans=[5000]
for k in range(1, min(Sa//Ma,Sb//Mb)+1):
    ans.append(dp[Ma*k][Mb*k])
if min(ans)==5000:
    print(-1)
else:
    print(min(ans))

Submission status: Time Limit Exceeded

Solution code:
N,Ma,Mb=map(int,input().split())
a=[0 for k in range(N)]
b=[0 for k in range(N)]
c=[0 for k in range(N)]

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

count=0
ans=[]
for k in range(2**N-1):
    count+=1
    bi=str(bin(count))
    A=0
    B=0
    C=0
    for j in range(1,len(bi)-1):
        if bi[-j]=="1":
            A+=a[j-1]
            B+=b[j-1]
            C+=c[j-1]
    if A*Mb==B*Ma and A!=0:
        ans.append(C)
if len(ans)>0:
    print(min(ans))
if ans==[]:
    print(-1)

Submission status: Time Limit Exceeded

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

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

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

for i in range(N):
    for j in range(401):
        for k in range(401):
            if j - abc[i][0] >= 0 and k - abc[i][1] >= 0:
                dp[i + 1][j][k] = min(dp[i][j][k], dp[i][j - abc[i][0]][k - abc[i][1]] + abc[i][2])
            else:
                dp[i + 1][j][k] = dp[i][j][k]
ans = inf
for a in range(1, 401):
    if a % Ma == 0:
        b = a // Ma * Mb
        if b <= 401:
            ans = min(ans, dp[N][a][b])
if ans == inf:
    ans = -1
print(ans)