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())
Items = [list(map(int, input().split())) for _ in range(N)]

# dp[i][a][b] := i番目の薬品までみて、タイプA: xグラム, タイプB: yグラム を手に入れるために必要な最小費用
dp = [[[float('inf')] * 401 for j in range(401)] for i in range(N + 1)]
dp[0][0][0] = 0
for i, (a, b, c) in enumerate(Items):
    for x in range(401):
        for y in range(401):
            dp[i + 1][x][y] = min(dp[i + 1][x][y], dp[i][x][y])
            if x + a > 400 or y + b > 400:
                continue
            dp[i + 1][x + a][y + b] = min(dp[i + 1][x + a][y + b], dp[i][x][y] + c)

ans = float('inf')
i = 1
while Ma * i <= 400 and Mb * i <= 400:
    ans = min(ans, dp[-1][Ma * i][Mb * i])
    i += 1
print(ans if ans != float('inf') else -1)

Submission status: Accepted

Solution code:
N, Ma, Mb = map(int, input().split())
dp = [[[10**18]*401 for _ in range(401)] for _ in range(N+1)]
dp[0][0][0] = 0

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

ans = 10**18

for i in range(401):
    for j in range(401):
        if i>0 and j>0 and i*Mb==j*Ma:
            ans = min(ans, dp[N][i][j])

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

Submission status: Accepted

Solution code:
n,ma,mb=map(int,input().split())
INF=10**18
dp=[[[INF for _ in range(401)] for _ in range(401)] for _ in range(n+1)]
ce=[[] for _ in range(n)]
for i in range(n):
  ce[i]=tuple(map(int,input().split()))
dp[0][0][0]=0
for k in range(n):
  for i in range(401):
    for j in range(401):
      a,b,c=ce[k]
      dp[k+1][i][j]=min(dp[k+1][i][j],dp[k][i][j])
      if i+a<401 and j+b<401:
        dp[k+1][i+a][j+b]=min(dp[k+1][i+a][j+b],dp[k][i][j]+c)
ans=INF
for i in range(1,401):
  for j in range(1,401):
    if i*mb==j*ma:ans=min(ans,dp[n][i][j])
if ans==INF:ans=-1
print(ans)

Submission status: Accepted

Solution code:
dp_n = 410
n, ma, mb = map(int, input().split())
dp = [[float('inf')]*dp_n for _ in range(dp_n)]
dp[0][0] = 0
for i in range(n):
    a, b, c = map(int, input().split())
    for j in reversed(range(dp_n)):
        for i in reversed(range(dp_n)):
            if dp[i][j] != float('inf'):
                try:
                    dp[i+a][j+b] = min(dp[i+a][j+b],dp[i][j]+c)
                except:
                    pass
res = float('inf')
for j in range(1,dp_n):
    for i in range(1,dp_n):
        if i*mb == j*ma:
            res = min(res,dp[i][j])
print(res if res != float('inf') else -1)

Submission status: Accepted

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

d={(0,0):0}
for i in range(n):
  nd={}
  for j in d:
    if j in nd:
      nd[j]=min(nd[j],d[j])
    else:
      nd[j]=d[j]
    s=(j[0]+item[i][0],j[1]+item[i][1])
    if s in nd:
      nd[s]=min(nd[s],d[j]+item[i][2])
    else:
      nd[s]=d[j]+item[i][2]
  d=nd
m=10**9
for i in d:
  if i==(0,0):
    continue
  if i[0]*mb==i[1]*ma:
    m=min(m,d[i])
if m==10**9:
  m=-1

print(m)

Submission status: Accepted

Solution code:
import math


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


def read_ints():
    return list(map(int, input().strip().split(' ')))


def read_into(*A):
    for arr, a in zip(A, read_ints()):
        arr.append(a)


def solve():
    """
    dp[400][400] = 160.000*10 = 1.600.000

    dp[x+a[i]][y+b[i]] = min(dp[x+a[i]][y+b[i]], c[i]+dp[x][y])
    dp[0][0] = 0
    """
    n, ma, mb = read_ints()
    A, B, C = [], [], []
    for _ in range(n):
        read_into(A, B, C)
    dp_upper_A, dp_upper_B = max(A)*n+1, max(B)*n+1
    dp = [
        [[math.inf]*dp_upper_B for _ in range(dp_upper_A)] for _ in range(n+1)
    ]
    dp[0][0][0] = 0
    for i in range(n):
        for x in range(dp_upper_A):
            for y in range(dp_upper_B):
                if dp[i][x][y] == math.inf:
                    continue
                dp[i+1][x][y] = min(dp[i+1][x][y], dp[i][x][y])
                dp[i+1][x+A[i]][y+B[i]] = min(dp[i+1][x+A[i]][y+B[i]], C[i]+dp[i][x][y])
    i = 1
    min_cost = math.inf
    while i*ma < dp_upper_A and i*mb < dp_upper_B:
        min_cost = min(min_cost, dp[n][i*ma][i*mb])
        i += 1
    return -1 if min_cost == math.inf else min_cost


if __name__ == '__main__':
    print(solve())

Submission status: Accepted

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

inf = 10**18
dp = [[[inf]*(411) for j in range(411)] for i in range(n+1)]
for i in range(n+1):
    dp[i][0][0] = 0
for i in range(n):
    for j in range(400):
        for k in range(400):
            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+a[i]][k+b[i]] = min(dp[i+1][j+a[i]][k+b[i]],dp[i][j][k]+c[i])

ans = 10**18
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**18:
    print(-1)
else:
    print(ans)

Submission status: Accepted

Solution code:
n, ma, mb = map(int, input().split())
abc = []
for _ in range(n):
    a, b, c = map(int, input().split())
    abc.append((a, b, c))
dp = {(0, 0): 0}
for a, b, c in abc:
    newdp = dp.copy()
    for (ka, kb), p in dp.items():
        k = (a+ka, b+kb)
        if k in newdp:
            newdp[k] = min(newdp[k], p+c)
        else:
            newdp[k] = p+c
    dp = newdp
INF = 10**10
ans = INF
for (a, b), c in dp.items():
    if ma*b!=mb*a or a==b==0:
        continue
    ans = min(ans, c)
if ans==INF:
    print(-1)
else:
    print(ans)

Submission status: Accepted

Solution code:
N, ma, mb = map(int, input().split())
a = [0]*N
b = [0]*N
c = [0]*N
NMAX = 40
ABMAX = 10
INF = 1000000
for i in range(N):
    a[i], b[i], c[i] = map(int, input().split())
dp = [[[INF]*(NMAX*ABMAX+1)for _ in range(NMAX*ABMAX+1)]for _ in range(N+1)]
dp[0][0][0] = 0
for i in range(N):
    for ca in range(NMAX*ABMAX+1):
        for cb in range(NMAX*ABMAX+1):
            if dp[i][ca][cb] == INF:
                continue
            dp[i+1][ca][cb] = min(dp[i+1][ca][cb], dp[i][ca][cb])
            dp[i+1][ca+a[i]][cb+b[i]
                             ] = min(dp[i+1][ca+a[i]][cb+b[i]], dp[i][ca][cb]+c[i])
ans = INF
for ca in range(1, NMAX*ABMAX+1):
    for cb in range(1, NMAX*ABMAX+1):
        if ca * mb == cb * ma:
            ans = min(ans, dp[N][ca][cb])
print(ans if ans != INF else -1)

Submission status: Accepted

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

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

MA=sum(a)
MB=sum(b)
dp=[[[float("inf") for i in range(MB+1)] for j in range(MA+1)] for k in range(N+1)]
dp[0][0][0]=0
for i in range(N):
  for j in range(MA):
    for k in range(MB):
      if dp[i][j][k]==float("inf"):
        continue
      dp[i+1][j][k]=min(dp[i+1][j][k],dp[i][j][k])
      dp[i+1][j+a[i]][k+b[i]]=min(dp[i+1][j+a[i]][k+b[i]],dp[i][j][k]+c[i])

ans=float("inf")
for i in range(1,MA+1):
  for j in range(1,MB+1):
    if i*Mb==j*Ma:
      ans=min(ans,dp[N][i][j])

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

Submission status: Accepted

Solution code:
import sys
import numpy as np
from collections import deque,defaultdict

inp=lambda v,w:v[0]*w[0]+v[1]*w[1]
isprop = lambda a,b: a[0]*b[1]==a[1]*b[0]
cwsum = lambda l:[sum([x[0] for x in l]), sum([x[1] for x in l])]
chmin = lambda a,b:(a,b)[b<a]
# cwsum = lambda l:np.sum(l,axis=0)
            
def main():
    N,Ma,Mb=map(int,input().split())
    infty=10**9
    ch=[list(map(int,input().split())) for _ in range(N)]
    p=[(-1)*Mb,Ma]
    # cand=[v[2] for v in ch if inp(p,v[:2])==0]
    # if cand:
        # m1=min(cand)
    # else:
        # m1=infty
    # ncand=[v for v in ch if inp(p,v[:2])!=0] #p方向への射影
    pch=[[inp(v[:2],p),v[2]] for v in ch]
    X=N*max([abs(w[0]) for w in pch])
    dp=[[infty]*(2*X+1) for _ in range(N)]
    for i in range(N):
        for j in range(2*X+1):
            if i==0 and j==X+pch[0][0]:
                dp[i][j]=pch[0][1]
            elif i>0 and j==X+pch[i][0]:
                dp[i][j]=chmin(dp[i-1][j],pch[i][1])
            elif i>0 and j>=pch[i][0] and j<=2*X+pch[i][0]:
                dp[i][j]=chmin(dp[i-1][j],dp[i-1][j-pch[i][0]]+pch[i][1])
            elif i>0:
                dp[i][j]=dp[i-1][j]
    #  print(ch)
    #  print(pch)
    #  print(dp)
    if dp[N-1][X]==infty:
        print(-1)
    else:
        print(dp[N-1][X])

if __name__=='__main__':
    main()

Submission status: Accepted

Solution code:
import sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(max(1000, 10**9))
write = lambda x: sys.stdout.write(x+"\n")


n, ma, mb = list(map(int, input().split()))
abc = [None]*n
for i in range(n):
    a,b,c = tuple(map(int, input().split()))
    abc[i] = (a*mb - b*ma, c)
abc.sort()
def halfcomb(l):
    n = len(l)
    n1 = n//2
    n2 = (n+1)//2
    l1 = []
    l2 = []
    def sub(v1, v2, i, bound, ll, ind=0):
        if i==bound:
            ll.append((v1,v2))
            return
        sub(v1, v2, i+1, bound, ll, ind)
        sub(v1+l[ind+i][0], v2+l[ind+i][1], i+1, bound, ll, ind)
    sub(0, 0, 0, n1, l1)
    sub(0, 0, 0, n2, l2, ind=n1)
    return l1, l2
l1, l2 = halfcomb(abc)
d2 = {}
for v,c in l2:
    if v in d2:
        d2[v] = min(d2[v], c)
    else:
        d2[v] = c
ans = float("inf")
for v,c in l1:
    if v==0 and c>0:
        ans = min(ans, c)
for v,c in l2:
    if v==0 and c>0:
        ans = min(ans, c)
        
for v,c in l1:
    if -v in d2 and c+d2[-v]>0:
        ans = min(ans, c+d2[-v])
if ans == float("inf"):
    ans = -1
print(ans)

Submission status: Accepted

Solution code:
import sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(max(1000, 10**9))
write = lambda x: sys.stdout.write(x+"\n")


n, ma, mb = list(map(int, input().split()))
abc = [None]*n
for i in range(n):
    a,b,c = tuple(map(int, input().split()))
    abc[i] = (a*mb - b*ma, c)
abc.sort()
def halfcomb(l):
    n = len(l)
    n1 = n//2
    n2 = (n+1)//2
    l1 = []
    l2 = []
    
    for b in range(1, 1<<n2):
        v11, v12 = 0, 0
        v21, v22 = 0, 0
        for i in range(n2):
            if b&1<<i:
                item = l[n1+i]
                v21+=item[0]
                v22+=item[1]
                if b<(1<<n1) and i<n1:
                    item = l[i]
                    v11+=item[0]
                    v12+=item[1]
        if b<(1<<n1):
            l1.append((v11,v12))
        l2.append((v21,v22))
    return l1, l2
l1, l2 = halfcomb(abc)
d2 = {}
for v,c in l2:
    if v in d2:
        d2[v] = min(d2[v], c)
    else:
        d2[v] = c
ans = float("inf")
for v,c in l1:
    if v==0:
        ans = min(ans, c)
for v,c in l2:
    if v==0:
        ans = min(ans, c)
        
for v,c in l1:
    if -v in d2:
        ans = min(ans, c+d2[-v])
if ans == float("inf"):
    ans = -1
print(ans)

Submission status: Accepted

Solution code:
N,M,L=map(int,input().split())
X=[list(map(int,input().split())) for i in range(N)]
INF=10**9
DP=[[INF]*411 for i in range(411)]
DP[0][0]=0
for i in range(N):
  for j in range(400,-1,-1):
    for k in range(401):
      DP[j+X[i][0]][k+X[i][1]]=min(DP[j+X[i][0]][k+X[i][1]],DP[j][k]+X[i][2])
P=INF
for i in range(1,401):
  if i*max(M,L)>400:
    break
  P=min(P,DP[i*M][i*L])
if P==INF:
  print(-1)
else:
  print(P)

Submission status: Accepted

Solution code:
N,A,B=map(int,input().split())
inf=float("inf")
dp=[[inf]*401 for _ in range(401)]
dp[0][0]=0
for i in range(N):
    a,b,c=map(int,input().split())
    for j in range(-1,-402,-1):
        for k in range(-1,-402,-1):
            if dp[j][k]!=inf:
                dp[j+a][k+b]=min(dp[j+a][k+b],dp[j][k]+c)
ans=inf
for i in range(1,401):
    for j in range(1,401):
        if i/j==A/B:
            ans=min(ans,dp[i][j])
if ans==inf:
    ans=-1
print(ans)

Submission status: Accepted

Solution code:
def getN():
    return int(input())
def getN():
    return int(input())
def getNM():
    return map(int, input().split())
def getList():
    return list(map(int, input().split()))
def getArray(intn):
    return [int(input()) for i in range(intn)]
def input():
    return sys.stdin.readline().rstrip()
def rand_N(ran1, ran2):
    return random.randint(ran1, ran2)
def rand_List(ran1, ran2, rantime):
    return [random.randint(ran1, ran2) for i in range(rantime)]
def rand_ints_nodup(ran1, ran2, rantime):
  ns = []
  while len(ns) < rantime:
    n = random.randint(ran1, ran2)
    if not n in ns:
      ns.append(n)
  return sorted(ns)

def rand_query(ran1, ran2, rantime):
  r_query = []
  while len(r_query) < rantime:
    n_q = rand_ints_nodup(ran1, ran2, 2)
    if not n_q in r_query:
      r_query.append(n_q)
  return sorted(r_query)

from collections import defaultdict, deque, Counter
from sys import exit
from decimal import *
import heapq
import math
from fractions import gcd
import random
import string
import copy
from itertools import combinations, permutations, product
from operator import mul
from functools import reduce
from bisect import bisect_left, bisect_right

import sys
sys.setrecursionlimit(1000000000)
mod = 10 ** 9 + 7

#############
# Main Code #
#############

N, Ma, Mb = getNM()
query = [getList() for i in range(N)]

# dp[i][j][l]: i個まで探索したあとで物質aをjグラム,物質bをlグラム生成する最少費用
dp = [[[float('inf')] * 501 for i in range(501)] for i in range(N + 1)]
dp[0][0][0] = 0

# 各薬品
for i in range(N):
    # 物質a
    for j in range(501):
        # 物質b
        for l in range(501):
            a, b, c = query[i]
            if j - a >= 0 and l - b >= 0:
                dp[i + 1][j][l] = min(dp[i][j][l], dp[i][j - a][l - b] + c)
            else:
                dp[i + 1][j][l] = dp[i][j][l]

ans = float('inf')
for j in range(1, 500):
    for l in range(1, 500):
        if Ma * l == Mb * j and dp[N][j][l] < 10 ** 9 + 7:
            ans = min(ans, dp[N][j][l])
if ans < 10 ** 9 + 7:
    print(ans)
else:
    print(-1)

Submission status: Accepted

Solution code:
n,ma,mb= map(int,input().split())
al=[]
bl=[]
cl=[]
for _ in range(n):
    a,b,c= map(int,input().split())
    al.append(a)
    bl.append(b)
    cl.append(c)
suma=sum(al)
MAX=999999999999
gmincost = [MAX]
def dfsMa(id,count,sel):
    if id==n:return
    dfsMa(id+1,count,sel)
    tempsum = al[id]+count
    bsum=costsum=0
    for j in sel+[id]:
        bsum+=bl[j]
        costsum+=cl[j]
    if costsum > gmincost[0]:
        return
    elif tempsum%ma == 0:
        k=tempsum//ma
        if bsum==k*mb:
            gmincost[0] = min(gmincost[0],costsum)
            return
    dfsMa(id+1,count+al[id],sel+[id])
    return
dfsMa(0,0,[])
if gmincost[0]==MAX:print(-1)
else:print(gmincost[0])

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline

N, Ma, Mb = map(int, input().split())
dp = [[[10**18]*(10*N+1) for _ in range(10*N+1)] for _ in range(N+1)]
dp[0][0][0] = 0

for i in range(N):
    a, b, c = map(int, input().split())
    
    for j in range(10*N+1):
        for k in range(10*N+1):
            dp[i+1][j][k] = min(dp[i+1][j][k], dp[i][j][k])
            
            if j+a<=10*N and k+b<=10*N:
                dp[i+1][j+a][k+b] = min(dp[i+1][j+a][k+b], dp[i][j][k]+c)
            
ans = 10**18

for i in range(10*N+1):
    for j in range(10*N+1):
        if i!=0 and j!=0 and i*Mb==j*Ma:
            ans = min(ans, dp[N][i][j])

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

Submission status: Accepted

Solution code:
N, A, B = map(int, input().split())
chem = []
for i in range(N):
    a, b, c = map(int, input().split())
    chem.append((a, b, c))

MAXX = N*10 + 1
MAXMONEY = 100*MAXX
money = [[MAXMONEY]*MAXX for _ in range(MAXX)]
ans = MAXMONEY

money[0][0] = 0
for i in range(N):
    a, b, cc = chem[i]
    for c1 in range(MAXX-1, -1, -1):
        for c2 in range(MAXX-1, -1, -1):
            if money[c1][c2] < MAXMONEY:
                newm = money[c1][c2] + cc
                if (c1 + a < MAXX) and (c2+b < MAXX) and (money[c1+a][c2+b] > newm):
                    money[c1 + a][c2 + b] = newm


rr = int(min((MAXX+0.9*A)//A, (MAXX+0.9*B)//B))
for bai in range(1, rr):
    if money[A*bai][B*bai] < ans:
        ans = money[A*bai][B*bai]

if ans >= MAXMONEY: ans = -1
print(ans)

Submission status: Accepted

Solution code:
N,ma,mb=map(int,(input().split()))
a,b,c=[0]*N,[0]*N,[0]*N
for i in range(N):
    a[i],b[i],c[i]=map(int,input().split())

MA=sum(a)
MB=sum(b)
dp=[[[float("inf") for i in range(MB+1)] for j in range(MA+1)] for k in range(N+1)]
dp[0][0][0]=0
for i in range(N):
    for j in range(MA):
        for k in range(MB):
            if dp[i][j][k]==float("inf"):
                continue
            dp[i+1][j][k]=min(dp[i+1][j][k],dp[i][j][k])
            dp[i+1][j+a[i]][k+b[i]]=min(dp[i+1][j+a[i]][k+b[i]],dp[i][j][k]+c[i])

ans=float("inf")
for i in range(1,MA+1):
    for j in range(1,MB+1):
        if i*mb==j*ma:
            ans=min(ans,dp[N][i][j])

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

Submission status: Accepted

Solution code:
N,MA,MB = map(int, input().split())
A = []
for _ in range(N):
  a,b,c = map(int, input().split())
  A.append([a,b,c])
  
# dp[i][ca][cb]
# i番目までのitemでaがca gram, bがcb gram 変えるときの最小コスト
# i:1-indexed. so max(i) = N
# maxca,maxcb = N*10
# max_cost(inf) > N *100
# N <= 40

gram_max = 410
cost_inf = 10000
dp = [[[ cost_inf for _ in range(gram_max)] for _ in range(gram_max)] for _ in range(N+1)]

dp[0][0][0] = 0
for i in range(1,N+1):
  a,b,c = A[i-1]
  for ca in range(0,gram_max):
    for cb in range(0,gram_max):
      dp[i][ca][cb] = min(dp[i][ca][cb], dp[i-1][ca][cb]) # なにもしない
      if ca-a >= 0 and cb-b >= 0:
        dp[i][ca][cb] = min(dp[i][ca][cb], dp[i-1][ca-a][cb-b] + c) 
        
ans = 10000
for ca in range(1,gram_max):
  for cb in range(1,gram_max):
    # ca:cb = MA:MB
    if MA*cb == MB*ca:
      ans = min(ans, dp[N][ca][cb])
      
print(ans if ans < 5000 else -1)

Submission status: Accepted

Solution code:
n,p,q=map(int,input().split())
M2=-10*(-n//2)
M1=10*(n//2)
dp1=[[float("INF")]*(M1+1)for i in range(M1+1)]
dp1[0][0]=0
for _ in range(n//2):
    a,b,c=map(int,input().split())
    for i in range(M1,a-1,-1):
        for j in range(M1,b-1,-1):
            dp1[i][j]=min(dp1[i][j],dp1[i-a][j-b]+c)
dp2=[[float("INF")]*(M2+1)for i in range(M2+1)]
dp2[0][0]=0
for _ in range(-(-n//2)):
    a,b,c=map(int,input().split())
    for i in range(M2,a-1,-1):
        for j in range(M2,b-1,-1):
            dp2[i][j]=min(dp2[i][j],dp2[i-a][j-b]+c)
ans=float("INf")
for i in range(M1+1):
    for j in range(M1+1):
        for c in range(max(1,-min(-i//p,-j//q)),M2//max(p,q)+1):
            ans=min(ans,dp1[i][j]+dp2[c*p-i][c*q-j])
print(ans if ans!= float("INF") else -1)

Submission status: Accepted

Solution code:
INF = float("inf")

N, Ma, Mb, *ABC = map(int, open(0).read().split())

M = 160010

dp = [0] + [INF] * M
for a, b, c in zip(*[iter(ABC)] * 3):
    T = dp[:]
    p = 401 * a + b
    for i, dpi in enumerate(dp):
        j = p + i
        if j > M:
            break
        if T[j] > dpi + c:
            T[j] = dpi + c
    dp = T

ans = INF
for i in range(1, M):
    a, b = divmod(i, 401)
    if Ma * b == Mb * a and ans > dp[i]:
        ans = dp[i]

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

Submission status: Accepted

Solution code:
import sys

readline = sys.stdin.readline
MOD = 10 ** 9 + 7
INF = float('INF')
sys.setrecursionlimit(10 ** 5)


def main():
    n, x, y = map(int, readline().split())
    mat = []

    for _ in range(n):
        a, b, c = map(int, readline().split())
        mat.append((a, b, c))

    dp = [[[INF] * 401 for _ in range(401)] for __ in range(n + 1)]
    dp[0][0][0] = 0

    for i in range(1, n + 1):
        a, b, c = mat[i - 1]
        for j in range(401):
            for k in range(401):
                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)

    ans = INF
    for i, j in zip(range(x, 401, x), range(y, 401, y)):
        ans = min(ans, dp[n][i][j])

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


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline

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

dp = [5000 for i in range(170000)]
dp[0] = 0

for a, b, c in abc:
    dpn = dp[:]
    for i in range(170000):
        nex = 401 * b + a + i
        if nex >= 170000:
            break
        dpn[nex] = min(dpn[nex], dp[i] + c)
    dp = dpn

ans = 50000

for i in range(1,170000):
    a = i % 401
    b = i // 401
    if ma * b == mb * a:
        ans = min(ans, dp[i])

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

Submission status: Accepted

Solution code:
N, Ma, Mb = map(int,input().split())
L = []
for _ in range(N):
    L.append( list(map(int,input().split())) )
dp = [[[10**10 for _ in range(601)] for _ in range(601)] for _ in range(N+10)]
dp[0][0][0] = 0

for l in range(N):
    for i in range(200):
        for j in range(200):
            dp[l+1][i][j] = min(dp[l+1][i][j],dp[l][i][j])
            dp[l+1][i+L[l][0]][j+L[l][1]] = min(dp[l+1][i+L[l][0]][j+L[l][1]],dp[l][i][j] + L[l][2])


ans = 10**10
for i in range(1,10000):
    try: ans = min(ans, dp[N][Ma*i][Mb*i])
    except: pass
if ans == 10**10: print(-1)
else: print(ans)

Submission status: Accepted

Solution code:
import sys
import numpy as np
input = sys.stdin.buffer.readline

INF = 10 ** 9

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

delta_c = [(Mb * a - Ma * b, c) for a, b, c in abcs]

cost = INF
positives = []
negatives = []
for delta, c in delta_c:
    if delta == 0:
        cost = min(cost, c)
    elif delta > 0:
        positives.append((delta, c))
    else:
        negatives.append((-delta, c))

dp_pos = np.full(401, INF, np.int64)
dp_pos[0] = 0
for delta, c in positives:
    dp_pos[delta:] = np.minimum(dp_pos[:-delta] + c, dp_pos[delta:])

dp_neg = np.full(401, INF, np.int64)
dp_neg[0] = 0
for delta, c in negatives:
    dp_neg[delta:] = np.minimum(dp_neg[:-delta] + c, dp_neg[delta:])

cost = min(cost, np.amin(dp_pos[1:] + dp_neg[1:]))
if cost >= INF:
    print(-1)
else:
    print(cost)

Submission status: Accepted

Solution code:
n,ma,mb=map(int,input().split())
abc=[list(map(int,input().split())) for _ in range(n)]
import numpy as np
dp=np.full((401,401),4001,int)
dp[0,0]=0
for a,b,c in abc:
  dp[a:,b:]=np.minimum(dp[a:,b:],dp[:-a,:-b]+c)
ma_,mb_=ma,mb
ans=4001
while max(ma_,mb_)<401:
  ans=min(ans,dp[ma_,mb_])
  ma_+=ma
  mb_+=mb
print(ans if ans<4001 else -1)

Submission status: Accepted

Solution code:
#!python3

import copy

LI = lambda: list(map(int, input().split()))

# input
N, Ma, Mb = LI()
ABC = [LI() for _ in range(N)]

INF = 10 ** 5


def main():
    w = [[INF] * 401 for _ in range(401)]
    w[0][0] = 0
    for a, b, c in ABC:
        l = copy.deepcopy(w)
        for j in range(a, 401):
            for k in range(b, 401):
                l[j][k] = min(w[j][k], w[j - a][k - b] + c)
        w = l

    ans = INF
    n = 400 // max(Ma, Mb) + 1
    for i in range(1, n):
        ans = min(ans, w[Ma * i][Mb * i])
    ans = -1 if ans == INF else ans
    print(ans)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
def main():
    n, ma, mb = map(int, input().split())
    arr = [list(map(int, input().split())) for _ in range(n)]
    dp = [{} for _ in range(n+1)]
    dp[0][(0, 0)] = 0
    for i in range(n):
        for ky in dp[i].keys():
            if ky in dp[i+1]:
                if dp[i+1][ky] > dp[i][ky]:
                    dp[i+1][ky] = dp[i][ky]
            else:
                dp[i+1][ky] = dp[i][ky]
            t = (ky[0]+arr[i][0], ky[1]+arr[i][1])
            if t in dp[i+1]:
                if dp[i+1][t] > dp[i][ky]+arr[i][2]:
                    dp[i+1][t] = dp[i][ky]+arr[i][2]
            else:
                dp[i+1][t] = dp[i][ky]+arr[i][2]
    ans = float("inf")
    for i in range(1, 41):
        t = (ma*i, mb*i)
        if t in dp[n]:
            if ans > dp[n][t]:
                ans = dp[n][t]
    if ans == float("inf"):
        print("-1")
    else:
        print(ans)

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
N, Ma, Mb = map(int, input().split())
A = [list(map(int, input().split())) for i in range(N)]
DP = [0]*(N+1)
for i in range(N+1):
    DP[i] = [[float("inf")]*(10*N+1) for i in range(10*N+1)]
for i in range(N+1):
    DP[i][0][0] = 0
for i in range(N):
    for j in range(1, 10*N+1):
        for k in range(1,10*N+1):
            if DP[i+1][j][k] > DP[i][j-A[i][0]][k-A[i][1]]+A[i][2] and j-A[i][0] >= 0 and k-A[i][1] >= 0:
               DP[i+1][j][k] = min(DP[i][j-A[i][0]][k-A[i][1]]+A[i][2], DP[i][j][k])
            else:
                DP[i+1][j][k] = DP[i][j][k]
kouho = set()
for i in range(1, 10*N+1):
    if Ma*i < 10*N+1 and Mb*i < 10*N+1:
        if DP[N][Ma*i][Mb*i] == float("inf"):
            continue
        else:
            kouho.add(DP[N][Ma*i][Mb*i])
    else:
        break
if len(kouho) == 0:
    print(-1)
else:
    print(min(kouho))

Submission status: Accepted

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())
    dp = [[10**18]*(n*10+1) for _ in [0]*(n*10+1)]
    dp[0][0] = 0
    for _ in range(n):
        a,b,c = map(int,ipt().split())
        for i in range(n*10+1-a):
            dpi = dp[n*10-i-a]
            dpni = dp[n*10-i]
            for j in range(n*10+1-b):
                if dpni[n*10-j] > dpi[n*10-j-b]+c:
                    dpni[n*10-j] = dpi[n*10-j-b]+c
    mi = 10**18
    for i in range(1,n*10//max(ma,mb)+1):
        m = dp[ma*i][mb*i]
        if m < mi:
            mi = m
    if mi == 10**18:
        print(-1)
    else:
        print(mi)
    return

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
n, ma, mb = map(int, input().split())
r = [0] * n
c = [0] * n
for i in range(n):
  a, b, c[i] = map(int, input().split())
  r[i] = a * mb - b * ma
dp = [[10 ** 9] * 4001 for i in range(n + 1)]
for i in range(n):
  for j in range(4001):
    dp[i+1][j] = min(dp[i+1][j], dp[i][j])
    if j == 2000:
      dp[i+1][j+r[i]] = min(dp[i+1][j+r[i]], c[i])
    if 0 <= j + r[i] <= 4000:
      dp[i+1][j+r[i]] = min(dp[i+1][j+r[i]], dp[i][j] + c[i])
if dp[n][2000] < 10 ** 9:
  print(dp[n][2000])
else:
  print(-1)

Submission status: Accepted

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 = [INF] * 10000

    for i in range(1,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
        if h1[dif] > tc: h1[dif] = tc

    ans = h1[0]

    for i in range(1,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
        if dif == 0:
            ans = min(ans,tc)
        else:
            ans = min(ans,h1[dif]+tc)

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

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
def resolve():
    import sys
    input = sys.stdin.readline
    # 整数 1 つ
    # n = int(input())
    # 整数複数個
    n, ma, mb = map(int, input().split())
    # 整数 N 個 (改行区切り)
    # N = [int(input()) for i in range(N)]
    # 整数 N 個 (スペース区切り)
    # N = list(map(int, input().split()))
    # 整数 (縦 H 横 W の行列)
    A = [list(map(int, input().split())) for i in range(n)]

    Cost = [[[5000] * 401 for _ in range(401)] for _ in range(n+1)]
    Cost[0][0][0] = 0

    for i in range(n):
        for j in range(400):
            for k in range(400):
                if j+A[i][0] <= 400 and k+A[i][1] <= 400:
                    Cost[i+1][j+A[i][0]][k+A[i][1]] = min(Cost[i+1][j+A[i][0]][k+A[i][1]], Cost[i][j][k]+A[i][2])
                Cost[i+1][j][k] = min(Cost[i+1][j][k], Cost[i][j][k])

    costmin = 5000
    for a in range(1,401):
        for b in range(1,401):
            if a * mb == b * ma:
                costmin = min(costmin, Cost[n][a][b])
    if costmin == 5000:
        print(-1)
    else:
        print(costmin)


resolve()