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:
# Python3 (3.4.3)
import sys
input = sys.stdin.readline

# -------------------------------------------------------------
# function
# -------------------------------------------------------------


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

# dp[a][b] : Aタイプが ag, Bタイプが bg となる 最小コスト
inf = float("inf")
dp = [[inf for _ in range(401)] for _ in range(401)]
dp[0][0] = 0

for a,b,c in ABC:
    for i in range(400,-1,-1):
        for j in range(400,-1,-1):
            if dp[i][j] != inf:
                # 薬品を使った方が安ければ更新する
                dp[i+a][j+b] = min(dp[i+a][j+b], dp[i][j] + c)

ans = inf
for i in range(1,401):
    for j in range(1,401):
        # i : j == Ma : Mb なら コストを更新
        if i*Mb == j*Ma:
            ans = min(ans, dp[i][j])

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

Submission status: Accepted

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

kusuri = []
cusum = [0]*(N+1)
for i in range(N):
  a, b, c = map(int, input().split())
  sa = a*Mb - b*Ma
  kusuri.append((sa, c))
  cusum[i+1] = cusum[i] + c

call = cusum[-1]
dp = [[call+1]*8001 for _ in range(41)]
dp[0][4000] = 0

cmin = call+1
for i, j in enumerate(kusuri):
  d = j[0]
  c = j[1]
  for k in range(4000-100*i, 4000+100*i+1):
    dp[i+1][k] = min(dp[i+1][k], dp[i][k])
    if k + d == 4000:
      cmin = min(cmin, dp[i][k]+c)
    dp[i+1][k+d] = min(dp[i+1][k+d], dp[i][k]+c)
    

if cmin == call+1:
  print(-1)
else:
  print(cmin)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
n, ma, mb = map(int, input().split())
inf = 10000
med = [tuple(map(int, input().split())) for _ in range(n)]
dp = [[[inf] * 401 for _ in range(401)] for _ in range(n+1)]
dp[0][0][0] = 0
for k in range(n):
    for i in range(401):
        for j in range(401):
            a, b, c = med[k]
            if i - a >= 0 and j - b >= 0:
                dp[k+1][i][j] = min(dp[k][i][j], dp[k][i-a][j-b] + c)
            else:
                dp[k+1][i][j] = dp[k][i][j]

ans = inf
for k in range(1, 401):
    if k * ma > 400 or k * mb > 400:
        break
    x, y = k * ma, k * mb
    ans = min(ans, dp[n][x][y])

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

Submission status: Accepted

Solution code:
import itertools

N,MA,MB = map(int,input().split())
arr = []

for i in range(N):
  l = list(map(int,input().split()))
  arr.append(l)
  
dp = [ [ [50000 for k in range(401)] for j in range(401)] for i in range(N+1) ]
dp[0][0][0] = 0
ans = 50000

for i,a,b in itertools.product(range(1,N+1),range(401),range(401)):
  A = arr[i-1][0]
  B = arr[i-1][1]
  C = arr[i-1][2]
  
  if A <= a and B <= b and dp[i-1][a-A][b-B] != 50000:
    dp[i][a][b] = min(dp[i-1][a][b],dp[i-1][a-A][b-B] + C)
  else:
    dp[i][a][b] = dp[i-1][a][b]

for a,b in itertools.product(range(401),range(401)):
    if a * MB == b * MA and a != 0 and b != 0:
      ans = min(ans,dp[-1][a][b])
    
if ans == 50000:
  print(-1)
else:
  print(int(ans))

Submission status: Accepted

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

import sys
# import time
# import math
# import numpy as np
# import scipy.sparse.csgraph as cs            # csgraph_from_dense(ndarray, null_value=inf), bellman_ford(G, return_predecessors=True), dijkstra, floyd_warshall
# import random                                # random, uniform, randint, randrange, shuffle, sample
# import string                                # ascii_lowercase, ascii_uppercase, ascii_letters, digits, hexdigits
# import re                                    # re.compile(pattern) => ptn obj; p.search(s), p.match(s), p.finditer(s) => match obj; p.sub(after, s)
# from bisect import bisect_left, bisect_right # bisect_left(a, x, lo=0, hi=len(a)) returns i such that all(val<x for val in a[lo:i]) and all(val>-=x for val in a[i:hi]).
# from collections import deque                # deque class. deque(L): dq.append(x), dq.appendleft(x), dq.pop(), dq.popleft(), dq.rotate()
# from collections import defaultdict          # subclass of dict. defaultdict(facroty)
# from collections import Counter              # subclass of dict. Counter(iter): c.elements(), c.most_common(n), c.subtract(iter)
# from datetime import date, datetime          # date.today(), date(year,month,day) => date obj; datetime.now(), datetime(year,month,day,hour,second,microsecond) => datetime obj; subtraction => timedelta obj
# from datetime.datetime import strptime       # strptime('2019/01/01 10:05:20', '%Y/%m/%d/ %H:%M:%S') returns datetime obj
# from datetime import timedelta               # td.days, td.seconds, td.microseconds, td.total_seconds(). abs function is also available.
# from copy import copy, deepcopy              # use deepcopy to copy multi-dimentional matrix without reference
# from functools import reduce                 # reduce(f, iter[, init])
# from functools import lru_cache              # @lrucache ...arguments of functions should be able to be keys of dict (e.g. list is not allowed)
# from heapq import heapify, heappush, heappop # built-in list. heapify(L) changes list in-place to min-heap in O(n), heappush(heapL, x) and heappop(heapL) in O(lgn).
# from heapq import nlargest, nsmallest        # nlargest(n, iter[, key]) returns k-largest-list in O(n+klgn).
# from itertools import count, cycle, repeat   # count(start[,step]), cycle(iter), repeat(elm[,n])
# from itertools import groupby                # [(k, list(g)) for k, g in groupby('000112')] returns [('0',['0','0','0']), ('1',['1','1']), ('2',['2'])]
# from itertools import starmap                # starmap(pow, [[2,5], [3,2]]) returns [32, 9]
# from itertools import product, permutations  # product(iter, repeat=n), permutations(iter[,r])
# from itertools import combinations, combinations_with_replacement
# from itertools import accumulate             # accumulate(iter[, f])
# from operator import itemgetter              # itemgetter(1), itemgetter('key')
# from fractions import gcd                    # for Python 3.4 (previous contest @AtCoder)



def main():
    mod = 1000000007                # 10^9+7
    inf = float('inf')              # sys.float_info.max = 1.79...e+308
    # inf = 2 ** 64 - 1             # (for fast JIT compile in PyPy) 1.84...e+19
    sys.setrecursionlimit(10**6)    # 1000 -> 1000000
    def input(): return sys.stdin.readline().rstrip()
    def ii():    return int(input())
    def mi():    return map(int, input().split())
    def mi_0():  return map(lambda x: int(x)-1, input().split())
    def lmi():   return list(map(int, input().split()))
    def lmi_0(): return list(map(lambda x: int(x)-1, input().split()))
    def li():    return list(input())
    
    
    n, ma, mb = mi()
    a_list = []
    b_list = []
    c_list = []
    for _ in range(n):
        a, b, c = mi()
        a_list.append(a)
        b_list.append(b)
        c_list.append(c)
    
    

    # dp[i+1][x][y] = i 番目までを使用して a を x[g], b を y[g] にする時のコスト
    dp = [[inf] * (sum(b_list) + 1) for _ in range(sum(a_list) + 1)]
    dp[0][0] = 0
    for i in range(n):
        for x in range(sum(a_list), 0, -1):
            for y in range(sum(b_list), 0, -1):
                i_a, i_b, i_c = a_list[i], b_list[i], c_list[i]
                if x - i_a >= 0 and y - i_b >= 0:
                    dp[x][y] = min(dp[x][y], dp[x-i_a][y-i_b] + i_c)

    # for line in dp:
    #     print(*line)
    
    ans = inf
    mul = min(sum(a_list) // ma, sum(b_list) // mb)
    for i in range(1, mul+1):
        # print(i)
        ans = min(ans, dp[i * ma][i * mb])
    
    print(ans) if ans != inf else print(-1)
    


if __name__ == "__main__":
    main()

Submission status: Accepted

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

INF = 10**10
dp = [[[INF for _ in range(400+5)] for _ in range(400+5)] for _ in range(n+5)]

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

for i in range(n):
    a, b, c = map(int, input().split())
    for ta in range(400+5-a):
        for tb in range(400+5-b):
            dp[i+1][ta][tb] = min(dp[i+1][ta][tb], dp[i][ta][tb])
            dp[i+1][ta+a][tb+b] = min(dp[i+1][ta+a][tb+b], dp[i][ta][tb]+c)

ans = INF
for i in range(1, n+1):
    t = 1
    while max(ma, mb)*t <= 400:
        ans = min(ans, dp[i][ma*t][mb*t])
        t += 1

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

Submission status: Accepted

Solution code:
from collections import defaultdict

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

d = defaultdict(lambda: float('inf'))
d[(0, 0)] = 0
for a, b, c in M:
    new_d = d.copy()
    for key_a, key_b in d:
        new_d[(a + key_a, b + key_b)] = min(new_d[(a + key_a, b + key_b)],
                                            d[(key_a, key_b)] + c)
    d = new_d

ans = float('inf')
for i in range(1, 401 // max(Ma, Mb)):
    ans = min(ans, d[(Ma * i, Mb * i)])
print(ans if ans != float('inf') else -1)

Submission status: Accepted

Solution code:
n,ma,mb = map(int, input().split())
abc = [list(map(int, input().split())) for i in range(n)]
INF = 10 ** 18
dp = [[[INF] * 500 for i in range(500)] for x in range(n+1)]
dp[0][0][0] = 0
for k,(a,b,c) in enumerate(abc):
  for i in range(400):
    for j in range(400):
      dp[k+1][i][j] = min(dp[k+1][i][j],dp[k][i][j])
      dp[k+1][i+a][j+b] = min(dp[k][i+a][j+b],dp[k][i][j]+c)
ans = INF
for i in range(1,500):
  Ma,Mb = i * ma, i * mb
  if Ma > 400 or Mb > 400:
    break
  ans = min(ans,dp[n][Ma][Mb])
if ans == INF:
  print(-1)
else:
  print(ans)

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10**9)
INF=10**18
def input():
    return sys.stdin.readline().rstrip()

def main():
    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())
    d={}
    ans=INF
    for i in range(2**(N//2)):
        ma,mb,cost=0,0,0
        for j in range(N//2):
            if (i>>j)&1:
                ma+=a[j]
                mb+=b[j]
                cost+=c[j]
        if ma!=0 and mb!=0 and ma*Mb==mb*Ma:
            ans=min(ans,cost)
        n=min(ma//Ma,mb//Mb)
        ma-=n*Ma
        mb-=n*Mb
        if (ma,mb) in d:
            d[(ma,mb)]=min(d[(ma,mb)],cost)
        else:
            d[(ma,mb)]=cost
    for i in range(1,2**(N-N//2)):
        ma,mb,cost=0,0,0
        for j in range(N-N//2):
            if (i>>j)&1:
                ma+=a[j+N//2]
                mb+=b[j+N//2]
                cost+=c[j+N//2]
        n=max(-(-ma//Ma),-(-mb//Mb))
        if (n*Ma-ma,n*Mb-mb) in d:
            ans=min(ans,cost+d[(n*Ma-ma,n*Mb-mb)])
    print(ans if ans!=INF else -1)

if __name__ == '__main__':
    main()

Submission status: Accepted

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

dp = [[[float("INF")]*(n*10+2) for i in range(n*10+2)] for j in range(n+1)]

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

for i in range(n):
    a,b,c = l[i]
    
    for j in range(n*10+1):
        for k in range(n*10+1):
            
            if j >= a and k >= b:
                dp[i+1][j][k] = min(dp[i][j][k],dp[i][j-a][k-b]+c)
            elif dp[i][j][k] != float("INF"):
                dp[i+1][j][k] = dp[i][j][k]
ans = float("INF")

for i in range(1,n*10+1):
    j = i*mb/ma
    if j%1 == 0 and j < n*10:
        ans = min(ans,dp[-1][i][int(j)])
if ans == float("INF"):
    print(-1)
else:
    print(ans)

Submission status: Accepted

Solution code:
#Mixing experiment
#dp[x][a][b]=Nこの商品のうちx番目まで見て、Aをaグラム、Bをbグラム得るために必要なお金の最小費用。
N,Ma,Mb=map(int,input().split())
D=[tuple(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 in range(N):
    a,b,c=D[i]
    for j in range(401):
        for k in range(401):
            if j>=a and k>=b:
                dp[i+1][j][k]=min(dp[i][j][k],dp[i][j-a][k-b]+c)
            else:
                dp[i+1][j][k]=dp[i][j][k]
ans=float("inf")
for i in range(1,401):
    if 0<Ma*i<=400 and 0<Mb*i<=400:
        ans=min(ans,dp[N][Ma*i][Mb*i])

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

Submission status: Accepted

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

abclist=[]
sum_a=sum_b=0
for _ in range(N):
  a,b,c=map(int,input().split())
  sum_a+=a
  sum_b+=b
  abclist.append((a,b,c))
#print(abclist)

dp=[[[float("inf")]*(sum_b+1) for _ in range(sum_a+1)] for _ in range(N+1)]
dp[0][0][0]=0
for i in range(1,N+1):
  a,b,c=abclist[i-1]
  for j in range(sum_a+1):
    for k in range(sum_b+1):
      dp[i][j][k]=dp[i-1][j][k]
      if j-a>=0 and k-b>=0:
        dp[i][j][k]=min(dp[i][j][k],dp[i-1][j-a][k-b]+c)
        
#print(dp[N])
Ma_orig=Ma
Mb_orig=Mb
answer=float("inf")
while Ma<=sum_a and Mb<=sum_b:
  answer=min(answer,dp[N][Ma][Mb])
  Ma+=Ma_orig
  Mb+=Mb_orig
  
if answer==float("inf"):
  print(-1)
else:
  print(answer)

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10 ** 5 + 10)


def input(): return sys.stdin.readline().strip()


def resolve():

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

    INF = 10**10  # INF+INFを計算してもオーバーフローしない範囲で大きく
    I, J, K = N, sum(A), sum(B)
    dp = [[[INF]*(K+1) for _ in range(J+1)] for _ in range(I+1)]
    dp[0][0][0] = 0
    for i in range(1, I+1):
        for j in range(J+1):
            for k in range(K+1):
                # i-1番目を選ぶ場合
                if j >= A[i-1] and k >= B[i-1]:
                    dp[i][j][k] = min(dp[i][j][k], dp[i-1]
                                      [j-A[i-1]][k-B[i-1]]+C[i-1])
                dp[i][j][k] = min(dp[i][j][k], dp[i-1][j][k])
    ans = INF
    for j in range(1,J+1):
        for k in range(1,K+1):
            if k*Ma == j*Mb and k*Ma!=0 and j*Mb!=0:
                ans = min(ans, dp[I][j][k])

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


resolve()

Submission status: Accepted

Solution code:
N, Ma, Mb = map(int, input().split(' '))
med = []
for _ in range(N):
    med.append(tuple(map(int, input().split(' '))))
inf = 10 ** 9 + 7

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

for k in range(N):
    (a, b, c) = med[k]
    for i in range(400, -1, -1):
        for j in range(400, -1, -1):
            if dp[i][j] != inf:
                dp[i + a][j + b] = min(dp[i + a][j + b], dp[i][j] + c)

ans = inf
for i in range(401):
    for j in range(401):
        if i == 0 or j == 0:
            continue
        if i * Mb == j * Ma:
            ans = min(ans, dp[i][j])
print(ans if ans != inf else -1)

Submission status: Accepted

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

N, Ma, Mb = map(int, input().split())
la, lb, lc = [], [], []
for _ in range(N):
    ai, bi, ci = map(int, input().split())
    la.append(ai)
    lb.append(bi)
    lc.append(ci)

sumA = sum(la)
sumB = sum(lb)

Inf = int(1e10)

dp = [[[Inf for _ in range(sumB + 1)] for _ in range(sumA + 1)] for _ in range(N + 1)]
dp[0][0][0] = 0


for i in range(1, N + 1):
    ai, bi, ci = la[i - 1], lb[i - 1], lc[i - 1]

    for j in range(sumA + 1):
        for k in range(sumB + 1):
            dp[i][j][k] = min(dp[i][j][k], dp[i - 1][j][k])
            if j - ai >= 0 and k - bi >= 0 and dp[i - 1][j - ai][k - bi] != Inf:
                dp[i][j][k] = min(dp[i][j][k], dp[i - 1][j - ai][k - bi] + ci)

ans = Inf
for j in range(1, sumA + 1):
    for k in range(1, sumB + 1):
        if Mb * j == Ma * k:
            ans = min(ans, dp[N][j][k])
if ans == Inf:
    print(-1)
else:
    print(ans)

Submission status: Accepted

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

N, Ma, Mb = map(int, input().split())
la, lb, lc = [], [], []
for _ in range(N):
    ai, bi, ci = map(int, input().split())
    la.append(ai)
    lb.append(bi)
    lc.append(ci)
sumA = sum(la)
sumB = sum(lb)

Inf = int(1e10)
dp = [[[Inf for _ in range(sumB + 1)] for _ in range(sumA + 1)] for _ in range(N + 1)]
dp[0][0][0] = 0

for i in range(N):
    ai, bi, ci = la[i], lb[i], lc[i]

    for j in range(sumA + 1):
        for k in range(sumB + 1):
            if dp[i][j][k] == Inf:
                continue
            dp[i+1][j][k] = min(dp[i+1][j][k], dp[i][j][k])
            dp[i+1][j+ai][k+bi] = min(dp[i+1][j+ai][k+bi], dp[i][j][k]+ci)


ans = Inf
for j in range(1, sumA + 1):
    for k in range(1, sumB + 1):
        if j * Mb == k * Ma:
            ans = min(ans, dp[N][j][k])

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

Submission status: Accepted

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(i*10+11):
        for bi in range(i*10+11):
            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: Accepted

Solution code:
N, A, B = map(int, input().split())
X = [list(map(int, input().split())) for _ in range(N)]

inf = 10 ** 9 + 7
dp = [[[inf] * 401 for _ in range(401)] for _ in range(N + 1)]
dp[0][0][0] = 0

# DP
for i in range(N):
    for j in range(401):
        for k in range(401):
            if j >= X[i][0] and k >= X[i][1]:
                dp[i + 1][j][k] = min(dp[i + 1][j][k], dp[i][j][k],
                                      dp[i][j - X[i][0]][k - X[i][1]] + X[i][2])
            else:
                dp[i + 1][j][k] = min(dp[i + 1][j][k], dp[i][j][k])

# Extract
ans = inf
for j in range(1, 401):
    for k in range(1, 401):
        if j * B == k * A:
            ans = min(ans, dp[-1][j][k])

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

Submission status: Accepted

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

    def enum(h, *, second_half: bool = False) -> set:
        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():
    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)

    t1 = [INF] * (INF * 2 + 1)
    t2 = [INF] * (INF * 2 + 1)
    for x, c in p1:
        t1[x] = min(t1[x], c)
    for x, c in p2:
        t2[x] = min(t2[x], c)

    ans = min(t1[0], t2[0])
    for x in range(-INF, INF + 1):
        ans = min(ans, t1[x] + t2[-x])

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


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
# https://atcoder.jp/contests/abc054/submissions/4360181

def main():
    from collections import defaultdict

    INF = 40 * 100 + 1

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

    memo = defaultdict(lambda: INF)

    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

        for key, value in tuple(memo.items()):
            memo[key + x] = min(
                memo[key + x],
                value + ci
            )  # 既存の組み合わせに混合
        memo[x] = min(memo[x], ci)  # 新規のみ

    print(memo[0] if 0 in memo else -1)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
def main():
    INF = 100 * 40 + 1
    MX = 4000

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

    dp = [[INF] * (MX * 2 + 1) for _ in range(2)]
    i, j = 0, 1
    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

        for k in range(-MX, MX + 1):
            dp[j][k] = dp[i][k]
        dp[j][x] = min(dp[j][x], ci)

        for k in range(-MX + x, MX + 1):
            dp[j][k] = min(
                dp[j][k],
                dp[i][k - x] + ci
            )
        i, j = j, i

    res = dp[i][0]
    print(-1 if res == INF else res)


if __name__ == '__main__':
    main()

Submission status: Accepted

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

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

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

n = N//2

d1 = [[5000]*401 for _ in range(401)]
d2 = [[5000]*401 for _ in range(401)]

for bit in range(1<<n):
    val_a = 0
    val_b = 0
    cost = 0
    for i in range(n):
        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] = min(d1[val_a][val_b],cost)

for bit in range(1<<(N-n)):
    val_a = 0
    val_b = 0
    cost = 0
    for i in range(N-n):
        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] = min(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 ka in range(401):
    for kb in range(401):
        if d1[ka][kb] != 5000:
            for v in vals[::-1]:
                left_a = v[0]-ka
                left_b = v[1]-kb
                if left_a < 0 or left_b < 0:
                    break
                if d1[ka][kb]+d2[left_a][left_b] < ans:
                    ans = d1[ka][kb]+d2[left_a][left_b]

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

Submission status: Accepted

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

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

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

n = N//2

d1 = [[5000]*401 for _ in range(401)]
d2 = [[5000]*401 for _ in range(401)]

for bit in range(1<<n):
    val_a = 0
    val_b = 0
    cost = 0
    for i in range(n):
        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] = min(d1[val_a][val_b],cost)

for bit in range(1<<(N-n)):
    val_a = 0
    val_b = 0
    cost = 0
    for i in range(N-n):
        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] = min(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 ka in range(401):
    for kb in range(401):
        for v in vals[::-1]:
            left_a = v[0]-ka
            left_b = v[1]-kb
            if left_a < 0 or left_b < 0:
                break
            if d1[ka][kb]+d2[left_a][left_b] < ans:
                ans = d1[ka][kb]+d2[left_a][left_b]

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

Submission status: Accepted

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

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

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

n = N//2

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

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

for bit in range(1<<(N-n)):
    val_a = 0
    val_b = 0
    cost = 0
    for i in range(N-n):
        if bit>>i&1:
            val_a += a[N-1-i]
            val_b += b[N-1-i]
            cost += c[N-1-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: Accepted

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

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

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

n = N//2

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

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]
    if cost < d1[(val_a,val_b)]:
        d1[(val_a,val_b)] = cost

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]
    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: Accepted

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

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

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

amax = sum(a)
bmax = sum(b)

# dp[i][j][k]: 薬品iまで見て，Aがjグラム，Bがkグラムの最小予算
dp = [[[5000]*(bmax+1) for _ in range(amax+1)] for _ in range(N)]
dp[0][a[0]][b[0]] = c[0]
dp[0][0][0] = 0
for i in range(1,N):
    for j in range(amax+1):
        for k in range(bmax+1):
            if j == k == 0:
                dp[i][j][k] = 0
            elif j-a[i] < 0 or k-b[i] < 0:
                dp[i][j][k] = dp[i-1][j][k]
            else:
                dp[i][j][k] = min(dp[i-1][j][k], dp[i-1][j-a[i]][k-b[i]]+c[i])

ans = 5000
now = 1
while True:
    if Ma*now <= amax and Mb*now <= bmax:
        if dp[N-1][Ma*now][Mb*now] < ans:
            ans = dp[N-1][Ma*now][Mb*now]
        now += 1
    else:
        break

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

Submission status: Accepted

Solution code:
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(10 ** 7)

n, ma, mb = map(int, readline().split())
inf = 40000
dp = [[[inf] * 401 for _ in range(401)] for _ in range(n + 1)]
ans = inf
dp[0][0][0] = 0
for i in range(n):
    a, b, c = map(int, readline().split())
    for j in range(401):
        for k in range(401):
            if dp[i][j][k] != inf:
                dp[i + 1][j + a][k + b] = min(dp[i + 1][j + a][k + b], dp[i][j][k] + c)
                dp[i + 1][j][k] = min(dp[i][j][k], dp[i + 1][j][k])
for i in range(1, 401):
    for j in range(1, 401):
        if i * mb == j * ma:
            if ans > dp[n][i][j]:
                ans = dp[n][i][j]
if ans == inf:
    ans = -1
print(ans)