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:
n,ma,mb=map(int,input().split())
dp=[[[10**4 for _ in range(401)] for __ in range(401)] for ___ in range(n+1)]
for i in range(n+1):
    dp[i][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 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 j in range(1,401):
    for k in range(1,401):
        if ma*k==mb*j:
            ans=min(ans,dp[n][j][k])
if ans==10**4:
    print(-1)
else:
    print(ans)

Submission status: Accepted

Solution code:
n, ma, mb = (int(x) for x in input().split())
ABC = [tuple(int(x) for x in input().split()) for _ in range(n)]
D1 = dict()
D2 = dict()
for (m, D, j) in ((n // 2, D1, 0), (n - n // 2, D2, n // 2)):
    for bit in range(1, 1<<m):
        sum_a = 0
        sum_b = 0
        sum_c = 0
        for i in range(m):
            if bit & 1<<i:
                a, b, c = ABC[i + j]
                sum_a += a
                sum_b += b
                sum_c += c
        s = mb * sum_a - ma * sum_b
        if s in D:
            D[s] = min(D[s], sum_c)
        else:
            D[s] = sum_c
ans = 10**18
if 0 in D1:
    ans = min(ans, D1[0])
if 0 in D2:
    ans = min(ans, D2[0])
for s in D1:
    if -s in D2:
        ans = min(ans, D1[s] + D2[-s])
if ans == 10**18:
    print(-1)
else:
    print(ans)

Submission status: Accepted

Solution code:
n, ma, mb = (int(x) for x in input().split())
ABC = [tuple(int(x) for x in input().split()) for _ in range(n)]
m = n // 2
D = dict()
E = dict()
for bit in range(1, 1<<m):
    sum_a = 0
    sum_b = 0
    sum_c = 0
    for i in range(m):
        if bit & 1<<i:
            a, b, c = ABC[i]
            sum_a += a
            sum_b += b
            sum_c += c
    s = mb * sum_a - ma * sum_b
    if s in D:
        D[s] = min(D[s], sum_c)
    else:
        D[s] = sum_c

k = n - m
for bit in range(1, 1<<k):
    sum_a = 0
    sum_b = 0
    sum_c = 0
    for i in range(k):
        if bit & 1<<i:
            a, b, c = ABC[m + i]
            sum_a += a
            sum_b += b
            sum_c += c
    s = mb * sum_a - ma * sum_b
    if s in E:
        E[s] = min(E[s], sum_c)
    else:
        E[s] = sum_c

ans = 10**18
if 0 in D:
    ans = min(ans, D[0])
if 0 in E:
    ans = min(ans, E[0])
for s, c in D.items():
    if -s in E:
        ans = min(ans, D[s] + E[-s])
if ans == 10**18:
    print(-1)
else:
    print(ans)

Submission status: Accepted

Solution code:
from fractions import Fraction
import sys
input = sys.stdin.readline

INF = float('inf')

N,A,B = list(map(int,input().split()))
data = [list(map(int, input().split())) for _ in range(N)]

P = []
M = []
Z = []
for a,b,c in data:
  if Fraction(a,b) == Fraction(A,B):
    Z.append(c)
  elif Fraction(a,b) > Fraction(A,B):
    P.append((a*2520-b*2520*A//B,c))
  else:
    M.append((-a*2520+b*2520*A//B,c))
    
dpP = [INF for i in range(1000000)]
dpP[0] = 0
for v,c in P:
  for i in range(1000000)[::-1]:
    if i>=v:
      dpP[i] = min(dpP[i],dpP[i-v]+c)

dpM = [INF for i in range(1000000)]
dpM[0] = 0
for v,c in M:
  for i in range(1000000)[::-1]:
    if i>=v:
      dpM[i] = min(dpM[i],dpM[i-v]+c)
      
ans = INF
if Z:
  ans = min(Z)
for i in range(1,1000000):
  ans = min(ans,dpP[i]+dpM[i])

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

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-

#############
# Libraries #
#############

import sys
input = sys.stdin.readline

import math
#from math import gcd
import bisect
import heapq
from collections import defaultdict
from collections import deque
from collections import Counter
from functools import lru_cache

#############
# Constants #
#############

MOD = 10**9+7
INF = float('inf')
AZ = "abcdefghijklmnopqrstuvwxyz"

#############
# Functions #
#############

######INPUT######
def I(): return int(input().strip())
def S(): return input().strip()
def IL(): return list(map(int,input().split()))
def SL(): return list(map(str,input().split()))
def ILs(n): return list(int(input()) for _ in range(n))
def SLs(n): return list(input().strip() for _ in range(n))
def ILL(n): return [list(map(int, input().split())) for _ in range(n)]
def SLL(n): return [list(map(str, input().split())) for _ in range(n)]


#####Shorten#####
def DD(arg): return defaultdict(arg)

#####Inverse#####
def inv(n): return pow(n, MOD-2, MOD)

######Combination######
kaijo_memo = []
def kaijo(n):
  if(len(kaijo_memo) > n): return kaijo_memo[n]
  if(len(kaijo_memo) == 0): kaijo_memo.append(1)
  while(len(kaijo_memo) <= n): kaijo_memo.append(kaijo_memo[-1] * len(kaijo_memo) % MOD)
  return kaijo_memo[n]

gyaku_kaijo_memo = []
def gyaku_kaijo(n):
  if(len(gyaku_kaijo_memo) > n): return gyaku_kaijo_memo[n]
  if(len(gyaku_kaijo_memo) == 0): gyaku_kaijo_memo.append(1)
  while(len(gyaku_kaijo_memo) <= n): gyaku_kaijo_memo.append(gyaku_kaijo_memo[-1] * pow(len(gyaku_kaijo_memo),MOD-2,MOD) % MOD)
  return gyaku_kaijo_memo[n]

def nCr(n,r):
  if n == r: return 1
  if n < r or r < 0: return 0
  ret = 1
  ret = ret * kaijo(n) % MOD
  ret = ret * gyaku_kaijo(r) % MOD
  ret = ret * gyaku_kaijo(n-r) % MOD
  return ret

######Factorization######
def factorization(n):
  arr = []
  temp = n
  for i in range(2, int(-(-n**0.5//1))+1):
    if temp%i==0:
      cnt=0
      while temp%i==0: 
        cnt+=1 
        temp //= i
      arr.append([i, cnt])
  if temp!=1: arr.append([temp, 1])
  if arr==[]: arr.append([n, 1])
  return arr

#####MakeDivisors######
def make_divisors(n):
  divisors = []
  for i in range(1, int(n**0.5)+1):
    if n % i == 0:
      divisors.append(i)
      if i != n // i: 
        divisors.append(n//i)
  return divisors

#####MakePrimes######
def make_primes(N):
  max = int(math.sqrt(N))
  seachList = [i for i in range(2,N+1)]
  primeNum = []
  while seachList[0] <= max:
    primeNum.append(seachList[0])
    tmp = seachList[0]
    seachList = [i for i in seachList if i % tmp != 0]
  primeNum.extend(seachList)
  return primeNum

#####GCD#####
def gcd(a, b):
    while b: a, b = b, a % b
    return a

#####LCM#####
def lcm(a, b):
    return a * b // gcd (a, b)

#####BitCount#####
def count_bit(n):
  count = 0
  while n:
    n &= n-1
    count += 1
  return count

#####ChangeBase#####
def base_10_to_n(X, n):
  if X//n: return base_10_to_n(X//n, n)+[X%n]
  return [X%n]

def base_n_to_10(X, n):
  return sum(int(str(X)[-i-1])*n**i for i in range(len(str(X))))

def base_10_to_n_without_0(X, n):
  X -= 1
  if X//n: return base_10_to_n_without_0(X//n, n)+[X%n]
  return [X%n]

#####IntLog#####
def int_log(n, a):
  count = 0
  while n>=a:
    n //= a
    count += 1
  return count

#############
# Main Code #
#############
from fractions import Fraction
N,A,B = IL()
data = ILL(N)

P = []
M = []
Z = []
for a,b,c in data:
  if Fraction(a,b) == Fraction(A,B):
    Z.append(c)
  elif Fraction(a,b) > Fraction(A,B):
    P.append((a*2520-b*2520*A//B,c))
  else:
    M.append((-a*2520+b*2520*A//B,c))
    
dpP = [INF for i in range(1000000)]
dpP[0] = 0
for v,c in P:
  for i in range(1000000)[::-1]:
    if i>=v:
      dpP[i] = min(dpP[i],dpP[i-v]+c)

dpM = [INF for i in range(1000000)]
dpM[0] = 0
for v,c in M:
  for i in range(1000000)[::-1]:
    if i>=v:
      dpM[i] = min(dpM[i],dpM[i-v]+c)
ans = INF
if Z:
  ans = min(Z)
for i in range(1,1000000):
  ans = min(ans,dpP[i]+dpM[i])

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

Submission status: Accepted

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

wmax=400
inf=10**10
dp=[[[inf]*(wmax+1) for _ in range(wmax+1)] for _ in range(n+1)]
dp[0][0][0]=0

for i in range(n):
    a,b,c=abc[i]
    for j in range(wmax+1):
        for k in range(wmax+1):
            dp[i+1][j][k]=dp[i][j][k]

            if j>=a and k>=b:
                dp[i+1][j][k]=min(dp[i+1][j][k],dp[i][j-a][k-b]+c)

ans=inf

for j in range(1,wmax+1):
    for k in range(1,wmax+1):
        if dp[n][j][k]>=inf:
            continue

        if ma*k==mb*j:
            ans=min(ans,dp[n][j][k])

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

Submission status: Accepted

Solution code:
import sys
from itertools import product
from collections import defaultdict

sys.setrecursionlimit(10 ** 7)
input = sys.stdin.readline
f_inf = float('inf')
mod = 10 ** 9 + 7


def resolve():
    n, Ma, Mb = map(int, input().split())
    ABC = [list(map(int, input().split())) for _ in range(n)]
    s = (n + 1) // 2
    t = n - s

    S = defaultdict(int)
    for pattern in product([0, 1], repeat=s):
        a = b = c = 0
        for idx, p in enumerate(pattern):
            if p == 1:
                a += ABC[idx][0]
                b += ABC[idx][1]
                c += ABC[idx][2]
        S[(a, b)] = min(S.get((a, b), f_inf), c)

    T = defaultdict(int)
    for pattern in product([0, 1], repeat=t):
        a = b = c = 0
        for idx, p in enumerate(pattern):
            if p == 1:
                a += ABC[s + idx][0]
                b += ABC[s + idx][1]
                c += ABC[s + idx][2]
        T[(a, b)] = min(T.get((a, b), f_inf), c)

    MAX_A = sum([a for a, _, _ in ABC])
    MAX_B = sum([b for _, b, _ in ABC])

    res = f_inf
    for k, v in S.items():
        a, b = k
        x, y = Ma, Mb
        while x <= MAX_A and y <= MAX_B:
            if T.get((x - a, y - b), -1) != -1:
                if not (a == b == 0 and x - a == x - b == 0):
                    cost = v + T[(x - a, y - b)]
                    res = min(res, cost)
            x += Ma
            y += Mb
    print(res if res != f_inf else -1)


if __name__ == '__main__':
    resolve()

Submission status: Accepted

Solution code:
N, ma, mb = map(int, input().split())
abc = [(-1, -1, -1)]
for _ in range(N):
    a, b, c = map(int, input().split())
    abc.append((a, b, c))

INF = float("inf")

# dp[n][i][j] :=
# n番目までの薬品の組み合わせで、Aがiグラム, 物質Bがjグラムとなる溶液の最小コスト
# N <= 40, a,b <= 10 なので、 i,j <= 400
dp = [[[INF for _ in range(401)] for _ in range(401)] for _ in range(N + 1)]
dp[0][0][0] = 0

for n in range(1, N + 1):
    a, b, c = abc[n]
    for i in range(401):
        for j in range(401):
            # n番目を買うことが出来る場合(=遷移元が存在する場合)
            # 買わない or 買う
            if i >= a and j >= b:
                dp[n][i][j] = min(dp[n - 1][i][j], dp[n - 1][i - a][j - b] + c)
            # n番目を買うことが出来ない場合(=遷移元が存在しない場合)
            else:
                dp[n][i][j] = dp[n - 1][i][j]

ans = INF
# i == j == 0　は不適、1から始める
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[N][i][j])

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

Submission status: Accepted

Solution code:
N,Ma,Mb=list(map(int,input().split()))
ABC=[tuple(map(int,input().split())) for i in range(N)]
inf=float("inf")
DP=[[inf]*401 for i in range(401)]
DP[0][0]=0
for a,b,c in ABC:
   for i in reversed(range(401)):
      for j in reversed(range(401)):
         if DP[i][j]!=inf:
            DP[i+a][j+b]=min(DP[i][j]+c,DP[i+a][j+b])
ans=inf
for i in range(1,401):
   for j in range(1,401):
      if Ma*j==Mb*i:
         ans=min(ans,DP[i][j])
print(-1 if ans==inf else ans)

Submission status: Accepted

Solution code:
INF=float('inf')
N,Ma,Mb=map(int,input().split())

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

for i in range(N):
    a,b,c=map(int,input().split())
    for A in reversed(range(401)):
        for B in reversed(range(401)):
            if B-b>=0 and A-a>=0:
                dp[A][B]=min(dp[A][B],dp[A-a][B-b]+c)
ans=INF
for i in range(1,401):
    if i*Ma>400 or i*Mb>400:
        break
    ans=min(ans,dp[Ma*i][Mb*i])
print(ans if ans!=INF else -1)

Submission status: Accepted

Solution code:
import sys
def MI(): return map(int,sys.stdin.readline().rstrip().split())


N,x,y = MI()
dp = [[[10**4]*401 for i in range(401)] for n in range(N+1)]
# dp[n][i][j] = 薬品1~nを用いて、タイプAをiグラム、タイプBをjグラムを作った時に必要な最小予算

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

z = min(dp[N][x*i][y*i] for i in range(1,min(400//x,400//y)+1))
print(-1 if z == 10**4 else z)

Submission status: Accepted

Solution code:
import sys
def MI(): return map(int,sys.stdin.readline().rstrip().split())


N,x,y = MI()
dp = [[[10**4]*401 for i in range(401)] for n in range(N+1)]
# dp[n][i][j] = 薬品1~nを用いて、タイプAをiグラム、タイプBをjグラムを作った時に必要な最小予算

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

z = min(dp[N][x*i][y*i] for i in range(1,min(400//x,400//y)+1))

if z == 10**4:
    print(-1)
else:
    print(z)

Submission status: Accepted

Solution code:
n, ma, mb = map(int, input().split())
x = [list(map(int, input().split())) for _ in range(n)]
x.insert(0, [0, 0, 0])
inf = 114514
dp = [[[inf] * (10 * n + 1) for _ in range(10 * n + 1)] for _ in range(n + 1)]
for i in range(n + 1):
    dp[i][0][0] = 0
suma, sumb = 0, 0
for i in range(1, n + 1):
    suma += x[i][0]
    sumb += x[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 >= x[i][0] and k >= x[i][1]:
                dp[i][j][k] = min(dp[i - 1][j][k], dp[i - 1][j - x[i][0]][k - x[i][1]] + x[i][2])
ans = 114514
for i in range(1, 10 * n + 1):
    for j in range(1, 10 * n + 1):
        if i * mb == j * ma:
            ans = min(ans, dp[n][i][j])
print(ans if not ans == 114514 else -1)

Submission status: Accepted

Solution code:
N,A,B = map(int,input().split())
X = [1<<20]*4040

for n in range(N):
  a,b,c = map(int,input().split())
  t = A*b-B*a
  X = [min(X[m],(0 if (m-t)%4040==0 else X[(m-t)%4040])+c) for m in range(4040)]

if 1<<18<X[0]:
  print(-1)
else:
  print(X[0])

Submission status: Accepted

Solution code:
import sys
from math import gcd
def input(): return sys.stdin.readline().strip()
sys.setrecursionlimit(10**9)

def main():
    N, Ma, Mb = map(int, input().split())
    """
    dp[i][j] = (0~iまでの薬品を使って、物質Bがjグラム余るようにするときの最小金額)
    jは整数になるとは限らないのでj=p/qと既約分数表示して(p, q)を辞書のキーとして保持する。
    """
    dp = {}
    a, b, c = map(int, input().split())
    p, q = b * Ma - a * Mb, Ma
    div = gcd(p, q)
    p, q = p // div, q // div
    dp[(p, q)] = c
    #print("i=0=>dp={}".format(dp))

    for i in range(1, N):
        dp2 = {}
        a, b, c = map(int, input().split())
        p, q = b * Ma - a * Mb, Ma
        div = gcd(p, q)
        p, q = p // div, q // div
        dp2[(p, q)] = c
        for p, q in dp:
            cost = dp[(p, q)]
            if (p, q) in dp2:
                dp2[(p, q)] = min(dp2[(p, q)], cost)
            else:
                dp2[(p, q)] = cost
            np, nq = p * Ma + b * q * Ma - a * q * Mb, q * Ma
            if np == 0:
                np, nq = 0, 1
            else:
                div = gcd(np, nq)
                np, nq = np // div, nq // div
            if (np, nq) in dp2:
                dp2[(np, nq)] = min(dp2[(np, nq)], cost + c)
            else:
                dp2[(np, nq)] = cost + c
        dp = dp2
        #print("i={}=>dp={}".format(i, dp))
    if (0, 1) in dp:
        print(dp[(0, 1)])
    else:
        print(-1)



if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
from sys import stdin
def input():
    return stdin.readline().strip()

n, ma, mb = map(int, input().split())
a, b, c = [], [], []
for _ in range(n):
    i, j, k = map(int, input().split())
    a.append(i)
    b.append(j)
    c.append(k)

sum_a = sum(a) + 1
sum_b = sum(b) + 1

# dpを商品を増やすごとに更新する
dp = [[float('inf')] * sum_b for _ in range(sum_a)]
dp[0][0] = 0

from copy import deepcopy
for i in range(n):
    new_dp = deepcopy(dp)
    ai, bi, ci = a[i], b[i], c[i]
    for x in range(sum_a - ai):
        for y in range(sum_b - bi):
            new_dp[x+ai][y+bi] = dp[x][y] + ci
    for x in range(sum_a):
        for y in range(sum_b):
            if dp[x][y] > new_dp[x][y]:
                dp[x][y] = new_dp[x][y]

ans = float('inf')
for x in range(1, sum_a):
    for y in range(1, sum_b):
        if x * mb == y * ma and dp[x][y] < ans:
            ans = dp[x][y]

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

Submission status: Accepted

Solution code:
import sys
readlines = sys.stdin.buffer.readlines
input = sys.stdin.buffer.readline
N, Ma, Mb = map(int, input().split())
X = [map(int, line.split()) for line in readlines()]
X = [(a*Mb-b*Ma, c) for a, b, c in X]

INF = 1 << 30
MAX = 10000
MID = MAX//2
dp = [INF]*(MAX+1)
ans = INF
for i, (x, c) in enumerate(X):
    if x == 0:
        ans = min(ans, c)
        continue

    if x > 0:
        for j in range(MAX, x-1, -1):
            dp[j] = min(dp[j], dp[j-x]+c)
    else:
        for j in range(MAX+x):
            dp[j] = min(dp[j], dp[j-x]+c)

    dp[MID+x] = min(dp[MID+x], c)

ans = min(ans, dp[MID])
print(ans if ans < INF else -1)

Submission status: Accepted

Solution code:
import sys
readlines = sys.stdin.buffer.readlines
input = sys.stdin.buffer.readline
N, Ma, Mb = map(int, input().split())
X = [tuple(map(int, line.split())) for line in readlines()]

INF = 1 << 30
x = [[INF]*201 for _ in [0]*201]
y = [[INF]*201 for _ in [0]*201]

n = N//2
X, Y = X[:n], X[n:]
for bit in range(1 << n):
    totA = totB = cost = 0
    for i in range(n):
        if bit >> i & 1:
            a, b, c = X[i]
            totA += a
            totB += b
            cost += c

    x[totA][totB] = min(x[totA][totB], cost)

for bit in range(1 << (N-n)):
    totA = totB = cost = 0
    for i in range(N-n):
        if bit >> i & 1:
            a, b, c = Y[i]
            totA += a
            totB += b
            cost += c

    y[totA][totB] = min(y[totA][totB], cost)

ans = INF
M = 405//max(Ma, Mb)
for i, t in enumerate(x):
    for j, s in enumerate(t):
        if s == INF:
            continue
        for k in range(1, M+1):
            I = k*Ma-i
            J = k*Mb-j
            if 0 <= I <= 200 and 0 <= J <= 200:
                ans = min(ans, s + y[I][J])

print(ans if ans < INF else -1)

Submission status: Accepted

Solution code:
import collections
import copy
INF = 10000

#入力
N, Ma, Mb = map(int, input().split())
medichine = [tuple(map(int, input().split())) for _ in range(N)]

dp = {}
#dp初期化
dp = collections.defaultdict(lambda:INF)
dp[0,0] = 0

for a, b, c in medichine:
    dp_ = copy.copy(dp)
    for ca,cb in dp.keys():
        dp_[ca+a, cb+b] = min(dp_[ca+a, cb+b], dp[ca,cb]+c)
    dp = dp_    

ans = INF
for ca,cb in dp.keys():
    if ca == cb == 0: continue
    if ca*Mb == cb*Ma:
        ans = min(ans, dp[ca,cb])
        
print(-1 if ans == INF else ans)

Submission status: Accepted

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

dp = [ [ [10**9]*401  for _ in range(401) ] for _ in range(n+1) ]
dp[0][0][0] = 0
for i in range(n):
    ai,bi,ci = abcl[i]
    for a in range(401):
        for b in range(401):
            dp[i+1][a][b] = min(dp[i][a][b], dp[i+1][a][b])
            if a+ai < 401 and b+bi < 401:
                dp[i+1][a+ai][b+bi] = min(dp[i][a][b] + ci, dp[i+1][a+ai][b+bi])


ans = 10**9
dp_row = dp[n]
for a in range(1,401):
    for b in range(1,401):
        if ma*b == mb*a:
            v = dp[n][a][b]
            ans = min(ans,v)

if ans == 10**9: ans = -1
print(ans)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
# でつoO(YOU PLAY WITH THE CARDS YOU'RE DEALT..)
import sys
INF = 10**10
def main(N, Ma, Mb, ABC):
    MX = 10 * N
    dp = [[[INF] * (MX + 1) for _ in range(MX + 1)] for __ in range(N + 1)]
    dp[0][0][0] = 0
    for i in range(N):
        ni = i + 1
        ma, mb, mc = ABC[i]
        for na in range(MX + 1):
            a = na - ma
            for nb in range(MX + 1):
                b = nb - mb
                dp[ni][na][nb] = dp[i][na][nb]
                if a >= 0 and b >= 0:
                    dp[ni][na][nb] = min(dp[ni][na][nb], dp[i][a][b] + mc)

    ans = INF
    for a in range(MX + 1):
        for b in range(MX + 1):
            if a == 0 and b == 0: continue
            if a * Mb == b * Ma:
                ans = min(ans, dp[N][a][b])
    if ans == INF:
        print(-1)
    else:
        print(ans)

if __name__ == '__main__':
    input = sys.stdin.readline
    N, Ma, Mb = map(int, input().split())
    ABC = [tuple(map(int, input().split())) for _ in range(N)]
    main(N, Ma, Mb, ABC)

Submission status: Accepted

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

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

INF = 5000
dp = [[INF] * 444 for _ in range(444)]


dp[0][0] = 0

for i in range(n):
    next = [[INF] * 444 for _ in range(444)]
    for j in range(401):
        for k in range(401):
            a, b, c = item[i]
            next[j + a][k + b] = min(next
                                     [j + a][k + b], dp[j][k] + c)
            next[j][k] = min(next[j][k], dp[j][k])
    dp = next

ans = INF
for i in range(1, 401):
    for j in range(1, 401):  # i : j == ma : mb
        if ma * j == i * mb:
            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())
abcl = []
for _ in range(n):
    a,b,c = map(int, input().split())
    abcl.append((a,b,c))

dp = [ [ [10**9]*401  for _ in range(401) ] for _ in range(n+1) ]
dp[0][0][0] = 0
for i in range(n):
    ai,bi,ci = abcl[i]
    for a in range(401):
        for b in range(401):
            if a+ai < 401 and b+bi < 401:
                dp[i+1][a][b] = min(dp[i][a][b], dp[i+1][a][b])
                dp[i+1][a+ai][b+bi] = min(dp[i][a][b] + ci, dp[i+1][a+ai][b+bi])


ans = 10**9
dp_row = dp[n]
for a in range(1,401):
    for b in range(1,401):
        if ma*b == mb*a:
            v = dp[n][a][b]
            ans = min(ans,v)

if ans == 10**9: ans = -1
print(ans)

Submission status: Accepted

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

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

    import math
    ans = INF
    for j in range(1, M):
        for k in range(1, M):
            g = math.gcd(j, k)
            if j//g == ma and k//g == mb:
                ans = min(ans, dp[n][j][k])
    if ans == INF:
        print(-1)
    else:
        print(ans)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
N,MA,MB = map(int,input().split())
ABC = [tuple(map(int,input().split())) for i in range(N)]

from collections import defaultdict
from copy import copy
d = defaultdict(lambda: float('inf'))
d[(0,0)] = 0
for a,b,c in ABC:
    d2 = copy(d)
    for (pa,pb),pc in d.items():
        d2[(pa+a, pb+b)] = min(d2[(pa+a, pb+b)], pc+c)
    d = d2

ans = float('inf')
for (a,b),c in d.items():
    if a==b==0: continue
    if a*MB == b*MA:
        ans = min(ans, c)
print(-1 if ans==float('inf') else ans)

Submission status: Accepted

Solution code:
import sys
from itertools import combinations
input = sys.stdin.readline

def main():
    n, ma, mb = map(int, input().split())
    dp = [[0]*401 for _ in range(401)]
    
    for _ in range(n):
        a, b, c = map(int, input().split())
        for i in range(400, -1, -1):
            for j in range(400, -1, -1):
                if i == 0 and j == 0:
                    if dp[a][b]:
                        dp[a][b] = min(dp[a][b], c)
                    else:
                        dp[a][b] = c
                if dp[i][j] and i+a <= 400 and j+b <= 400:
                    if dp[i+a][j+b]:
                        dp[i+a][j+b] = min(dp[i+a][j+b], dp[i][j]+c)
                    else:
                        dp[i+a][j+b] = dp[i][j] + c
    
    ans = 1000000
    x, y = ma, mb
    while x <= 400 and y <= 400:
        if dp[x][y]:
            ans = min(dp[x][y], ans)
        x += ma
        y += mb
    if ans == 1000000:
        print(-1)
    else:
        print(ans)
    
if __name__ == "__main__":
    main()

Submission status: Accepted

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

dp = [[[10**8 for cb in range(420)] for ca in range(420)]
      for i in range(N + 1)]
dp[0][0][0] = 0

for i in range(N):
    for ca in range(400):
        for cb in range(400):
            dp[i+1][ca][cb] = min(dp[i+1][ca][cb], dp[i][ca][cb])
            dp[i+1][ca+items[i][0]][cb+items[i][1]] = \
                min(dp[i+1][ca+items[i][0]][cb+items[i][1]],
                    dp[i][ca][cb]+items[i][2])


ans = 10**8
for ca in range(1, 401):
    if ca*Mb % Ma == 0 and ca*Mb//Ma <= 400:
        ans = min(ans, dp[N][ca][ca*Mb//Ma])
if ans == 10**8:
    print(-1)
else:
    print(ans)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
def main():
    N, Ma, Mb = map(int, input().split())
    a = [None] * N
    b = [None] * N
    c = [None] * N
    for i in range(N):
        a[i], b[i], c[i] = map(int, input().split())

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

    for i in range(N):
        for j in range(400,-1,-1):# 後ろから更新すること
            for k in range(400,-1,-1):
                if j - a[i] >= 0 and k - b[i] >= 0:
                    dp[j][k] = min(dp[j][k], dp[j-a[i]][k-b[i]]+c[i])
    
    ans = INF
    for j in range(400):
        for k in range(400):
            if j*Mb == k*Ma != 0:
                ans = min(ans,dp[j][k])
    print(ans) if ans < INF else print(-1)

if __name__ == "__main__":
    main()

Submission status: Accepted

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

def main():
    N, Ma, Mb = map(int, input().split())
    a = [None] * N
    b = [None] * N
    c = [None] * N
    for i in range(N):
        a[i], b[i], c[i] = map(int, input().split())

    INF = 10**12
    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(400,-1,-1):# 後ろから更新すること
            for k in range(400,-1,-1):
                dp[i+1][j][k] = min(dp[i+1][j][k], dp[i][j][k])
                if j - a[i] >= 0 and k - b[i] >= 0:
                    dp[i+1][j][k] = min(dp[i+1][j][k], dp[i][j-a[i]][k-b[i]]+c[i])
    
    ans = INF
    for j in range(400):
        for k in range(400):
            if j*Mb == k*Ma != 0:
                ans = min(ans,dp[N][j][k])
    print(ans) if ans < INF else print(-1)

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
N,MA,MB = map(int,input().split())
ABC = [tuple(map(int,input().split())) for i in range(N)]

INF = float('inf')
from collections import defaultdict
dp = defaultdict(lambda: INF)
dp[(0,0)] = 0
for a,b,c in ABC:
    dp2 = defaultdict(lambda: INF)
    for (pa,pb),pc in dp.items():
        dp2[(pa,pb)] = min(dp2[(pa,pb)], pc)
        dp2[(pa+a, pb+b)] = min(dp2[(pa+a, pb+b)], pc+c)
    dp = dp2

ans = INF
for i in range(1,401):
    ans = min(ans, dp[(MA*i, MB*i)])
print(-1 if ans==INF else ans)