Problem:


Score : 400 points

Problem Statement

Dolphin is planning to generate a small amount of a certain chemical substance C.

In order to generate the substance C, he must prepare a solution which is a mixture of two substances A and B in the ratio of M_a:M_b.

He does not have any stock of chemicals, however, so he will purchase some chemicals at a local pharmacy.

The pharmacy sells N kinds of chemicals. For each kind of chemical, there is exactly one package of that chemical in stock.

The package of chemical i contains a_i grams of the substance A and b_i grams of the substance B, and is sold for c_i yen (the currency of Japan).

Dolphin will purchase some of these packages. For some reason, he must use all contents of the purchased packages to generate the substance C.

Find the minimum amount of money required to generate the substance C.

If it is not possible to generate the substance C by purchasing any combination of packages at the pharmacy, report that fact.  

Constraints

1≦N≦40 

1≦a_i,b_i≦10 

1≦c_i≦100 

1≦M_a,M_b≦10 

gcd(M_a,M_b)=1

a_i, b_i, c_i, M_a and M_b are integers.

Input

The input is given from Standard Input in the following format:

N M_a M_b  
a_1 b_1 c_1  
a_2 b_2 c_2
:  
a_N b_N c_N  

Output

Print the minimum amount of money required to generate the substance C. If it is not possible to generate the substance C, print -1 instead.

Sample Input 1

3 1 1
1 2 1
2 1 2
3 3 10

Sample Output 1

3

The amount of money spent will be minimized by purchasing the packages of chemicals 1 and 2.

In this case, the mixture of the purchased chemicals will contain 3 grams of the substance A and 3 grams of the substance B, which are in the desired ratio: 3:3=1:1.

The total price of these packages is 3 yen.  

Sample Input 2

1 1 10
10 10 10

Sample Output 2

-1

The ratio 1:10 of the two substances A and B cannot be satisfied by purchasing any combination of the packages. Thus, the output should be -1.



Sample input:
3 1 1
1 2 1
2 1 2
3 3 10


Sample output:
3

Submission status: Time Limit Exceeded

Solution code:
n,ma,mb = (int(i) for i in input().split())
dp = [[[float("inf") for i in range(10*n+1)] for i in range(10*n+1)] for i in range(n+1)]
dp[0][0][0],ans = 0,float("inf")
for i in range(1,n+1):
	x,y,c = (int(l) for l in input().split())
	for j in range(10*(i-1)+1):
		for k in range(10*(i-1)+1):
			if dp[i-1][j][k]!=float("inf"):
				dp[i][j][k] = min(dp[i-1][j][k],dp[i][j][k])
				dp[i][j+x][k+y] = min(dp[i][j+x][k+y],dp[i-1][j][k]+c)
for i in range(ma,10*n+1,ma):
	if i*mb//ma<=10*n: ans=min(ans,dp[n][i][i*mb//ma])
if ans==float("inf"): print(-1)
else: print(ans)

Submission status: Time Limit Exceeded

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

Submission status: Time Limit Exceeded

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

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
def inpl(): return map(int, input().split())

N, Ma, Mb = inpl()
INF = 4001

DP = [[INF]*(411) for _ in range(411)]
DP[0][0] = 0

for n in range(N):
    DP2 = [[INF]*(411) for _ in range(411)]
    a, b, c = inpl()
    for i in range(10*(n+1) + 1):
        for j in range(10*(n+1) + 1):
            DP2[i][j] = min(DP[i][j], DP2[i][j])
            DP2[i+a][j+b] = min(DP[i+a][j+b], DP[i][j] + c)
    DP = DP2

x = 1
ans = INF
while Ma*x <= 400 and Mb*x <= 400:
    ans = min(ans, DP[Ma*x][Mb*x])
    
    x += 1

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

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
def inpl(): return map(int, input().split())

N, Ma, Mb = inpl()
INF = 4001

DP = [[INF]*(411) for _ in range(411)]
DP[0][0] = 0

for _ in range(N):
    DP2 = [[INF]*(411) for _ in range(411)]
    a, b, c = inpl()
    for i in range(400):
        for j in range(400):
            DP2[i][j] = min(DP[i][j], DP2[i][j])
            DP2[i+a][j+b] = min(DP[i+a][j+b], DP[i][j] + c)
    DP = DP2

x = 1
ans = INF
while Ma*x <= 400 and Mb*x <= 400:
    ans = min(ans, DP[Ma*x][Mb*x])
    x += 1

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

Submission status: Time Limit Exceeded

Solution code:
n,ma,mb=map(int,input().split())
lista=[]
listb=[]
listc=[]
y=0
z=0
for i in range(n):
    a,b,c=map(int,input().split())
    lista.append(a)
    listb.append(b)
    listc.append(c)
    y+=a
    z+=b
x=max(y,z)
dp=[[[float('inf') for i in range(n+1)]for i\
 in range(x+1)]for i in range(x+1)]
dp[0][0][0]=0
for i in range(n):
    for a in range(x+1):
        for b in range(x+1):
            if dp[a][b][i]==float('inf'):
                continue
            else:
                dp[a][b][i+1]=min(dp[a][b][i],dp[a][b][i+1])
                dp[a+lista[i]][b+listb[i]][i+1]=min(dp[a][b][i]+listc[i],dp[a+lista[i]][b+listb[i]][i+1]+listc[i])

cost=float('inf')
i=1
while 1:
    if ma*i<x+1 and mb*i<x+1:
        cost=min(cost,dp[ma*i][mb*i][n])
        i+=1
    else:
        break

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

Submission status: Time Limit Exceeded

Solution code:
n,ma,mb=map(int,input().split())
lista=[]
listb=[]
listc=[]
for i in range(n):
    a,b,c=map(int,input().split())
    lista.append(a)
    listb.append(b)
    listc.append(c)
x=max(sum(lista),sum(listb))
dp=[[[float('inf') for i in range(n+1)]for i\
 in range(x+1)]for i in range(x+1)]
dp[0][0][0]=0
for i in range(n):
    for a in range(x+1):
        for b in range(x+1):
            if dp[a][b][i]==float('inf'):
                continue
            else:
                dp[a][b][i+1]=min(dp[a][b][i],dp[a][b][i+1])
                dp[a+lista[i]][b+listb[i]][i+1]=min(dp[a][b][i]+listc[i],dp[a+lista[i]][b+listb[i]][i+1]+listc[i])

cost=float('inf')
i=1
while 1:
    if ma*i<x+1 and mb*i<x+1:
        cost=min(cost,dp[ma*i][mb*i][n])
        i+=1
    else:
        break

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

Submission status: Time Limit Exceeded

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

dp=[[[float('inf') for i in range(n+1)]for i\
 in range(401)]for i in range(401)]
dp[0][0][0]=0
for i in range(n):
    for a in range(401):
        for b in range(401):
            if dp[a][b][i]==float('inf'):
                continue
            else:
                dp[a][b][i+1]=min(dp[a][b][i],dp[a][b][i+1])
                dp[a+lista[i]][b+listb[i]][i+1]=min(dp[a][b][i]+listc[i],dp[a+lista[i]][b+listb[i]][i+1])

cost=float('inf')
i=1
while 1:
    if ma*i<401 and mb*i<401:
        cost=min(cost,dp[ma*i][mb*i][n])
        i+=1
    else:
        break

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

Submission status: Time Limit Exceeded

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

dp=[[[float('inf') for i in range(n+1)]for i\
 in range(401)]for i in range(401)]
for i in range(n+1):
    dp[0][0][0]=0
for i in range(n):
    for a in range(401):
        for b in range(401):
            if dp[a][b][i]==float('inf'):
                continue
            else:
                dp[a][b][i+1]=min(dp[a][b][i],dp[a][b][i+1])
                dp[a+lista[i]][b+listb[i]][i+1]=dp[a][b][i]+listc[i]
cost=float('inf')
i=1
while 1:
    if ma*i<401 and mb*i<401:
        cost=min(cost,dp[ma*i][mb*i][n])
        i+=1
    else:
        break

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

Submission status: Time Limit Exceeded

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

dp=[[[float('inf') for i in range(n+1)]for i\
 in range(401)]for i in range(401)]
for i in range(n+1):
    dp[0][0][0]=0
for i in range(n):
    for a in range(401):
        for b in range(401):
            if dp[a][b][i]==float('inf'):
                continue
            else:
                dp[a][b][i+1]=min(dp[a][b][i],dp[a][b][i+1])
                dp[a+lista[i]][b+listb[i]][i+1]=dp[a][b][i]+listc[i]
cost=float('inf')
for a in range(1,401):
    if float.is_integer(a*mb/ma) and a*mb/ma<=401:
            cost=min(cost,dp[a][int(a*mb/ma)][n])
if cost==float('inf'):
    print(-1)
else:
    print(cost)

Submission status: Time Limit Exceeded

Solution code:
n,ma,mb=map(int,input().split())
lista=[]
listb=[]
listc=[]
for i in range(n):
    a,b,c=map(int,input().split())
    lista.append(a)
    listb.append(b)
    listc.append(c)
x=sum(lista)
y=sum(listb)
z=0
w=0
dp=[[[float('inf') for i in range(n+1)]for i\
 in range(y+1)]for i in range(x+1)]
for i in range(n+1):
    dp[0][0][i]=0
for i in range(1,n+1):
    for a in range(x+1):
        for b in range(y+1):
            if a-lista[i-1]>=0 and b-listb[i-1]>=0:
                dp[a][b][i]=min(dp[a][b][i-1],dp[a-lista[i-1]][b-listb[i-1]][i-1]+listc[i-1])
            else:
                dp[a][b][i]=dp[a][b][i-1]
cost=float('inf')
for a in range(1,x+1):
    if float.is_integer(a*mb/ma) and a*mb/ma<=y+1:
            cost=min(cost,dp[a][int(a*mb/ma)][n])
if cost==float('inf'):
    print(-1)
else:
    print(cost)

Submission status: Time Limit Exceeded

Solution code:
n,ma,mb=map(int,input().split())
lista=[]
listb=[]
listc=[]
for i in range(n):
    a,b,c=map(int,input().split())
    lista.append(a)
    listb.append(b)
    listc.append(c)
x=sum(lista)
y=sum(listb)
dp=[[[float('inf') for i in range(n+1)]for i\
 in range(y+1)]for i in range(x+1)]
for i in range(n+1):
    dp[0][0][i]=0
for i in range(1,n+1):
    for a in range(x+1):
        for b in range(y+1):
            if a-lista[i-1]>=0 and b-listb[i-1]>=0:
                dp[a][b][i]=min(dp[a][b][i-1],dp[a-lista[i-1]][b-listb[i-1]][i-1]+listc[i-1])
            else:
                dp[a][b][i]=dp[a][b][i-1]
cost=float('inf')
for a in range(1,x+1):
    if float.is_integer(a*mb/ma) and a*mb/ma<=y+1:
            cost=min(cost,dp[a][int(a*mb/ma)][n])
if cost==float('inf'):
    print(-1)
else:
    print(cost)

Submission status: Time Limit Exceeded

Solution code:
N, Ma, Mb = map(int, input().split())
A, B, C = [], [], []
for i in range(N):
    ai, bi, ci = map(int, input().split())
    A.append(ai)
    B.append(bi)
    C.append(ci)

INF = float('inf')
dp = [[[INF]*401 for i in range(401)] for j in range(N+1)]
dp[0][0][0] = 0

for i in range(1, N+1):
    for a in range(1, 401):
        if A[i-1] > a:
            continue
        for b in range(1, 401):
            if A[i-1] <= a and B[i-1] <= b:
                dp[i][a][b] = min(dp[i-1][a][b], dp[i-1][a-A[i-1]][b-B[i-1]] + C[i-1])

ans = INF
for i in range(1, 401):
    target_a = Ma * i
    target_b = Mb * i
    if target_a > 400 or target_b > 400:
        break
    ans = min(ans, dp[N][target_a-1][target_b-1])

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

Submission status: Time Limit Exceeded

Solution code:
N, Ma, Mb = map(int, input().split())
A, B, C = [], [], []
for i in range(N):
    ai, bi, ci = map(int, input().split())
    A.append(ai)
    B.append(bi)
    C.append(ci)

INF = float('inf')
dp = [[[INF]*401 for i in range(401)] for j in range(N+1)]
dp[0][0][0] = 0

for i in range(1, N+1):
    for a in range(1, 401):
        for b in range(1, 401):
            if A[i-1] <= a and B[i-1] <= b:
                dp[i][a][b] = min(dp[i-1][a][b], dp[i-1][a-A[i-1]][b-B[i-1]] + C[i-1])
            else:
                dp[i][a][b] = dp[i-1][a][b]

ans = INF
for i in range(1, 401):
    target_a = Ma * i
    target_b = Mb * i
    if target_a > 400 or target_b > 400:
        break
    ans = min(ans, dp[N][target_a-1][target_b-1])

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

Submission status: Time Limit Exceeded

Solution code:
N,Ma,Mb=map(int,input().split())
Med=[]
for i in range(N):
  a=[int(x) for x in input().split()]
  Med.append(a)
  
#[i]まででMa=[j],Mb=[k]を作る場合の最小のコストdp
#dp[i+1][j+Ma][k+Mb]=min(dp[i][j+Ma][k+Mb],dp[i][j][k]+Cost)
#リストをinfで初期化。inf=作れない配合なので、continue。初期値はdp[0][0][0]=0
dp=[[[float('inf') for j in range(401)] for k in range(401)] for i in range(N+1)]
dp[0][0][0]=0

for i in range(N):
  for j in range(401):
    for k in range(401):
      if dp[i][j][k]==float('inf'):
        continue
      dp[i+1][j][k]=min(dp[i][j][k],dp[i+1][j][k])
      dp[i+1][j+Med[i][0]][k+Med[i][1]]=min(dp[i][j+Med[i][0]][k+Med[i][1]],dp[i][j][k]+Med[i][2])

ans=float('inf')
for i in range(1,N+1):
  if i*Ma<401 and i*Mb<401:
    ans=min(ans,dp[N][i*Ma][i*Mb])
if ans==float('inf'):
  print(-1)
else:
  print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict
N,Ma,Mb=map(int,raw_input().split())
A=[]
B=[]
C=[]
a_sum=0
b_sum=0
for i in range(N):
	a,b,c=map(int,raw_input().split())
	A.append(a)
	B.append(b)
	C.append(c)
	a_sum+=a
	b_sum+=b

dp=defaultdict(lambda: float("inf"))
dp[(0,0,0)]=0


for k in range(1,N+1):
	for x in range(a_sum+1):
		for y in range(b_sum+1):
			dp[(k,x,y)]=min( dp[(k,x,y)], dp[(k-1,x,y)] )
			if x-A[k-1]>=0 and y-B[k-1]>=0:
				dp[(k,x,y)]=min( dp[(k-1,x,y)], dp[(k-1, x-A[k-1], y-B[k-1])]+C[k-1] )


ans=float("inf")
for x in range(1,a_sum+1):
	for y in range(1,b_sum+1):
		if x*Mb==y*Ma:
			ans=min(ans,dp[(N, x, y)])

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

Submission status: Time Limit Exceeded

Solution code:
N,Ma,Mb=map(int,raw_input().split())
A=[]
B=[]
C=[]
a_sum=0
b_sum=0
for i in range(N):
	a,b,c=map(int,raw_input().split())
	A.append(a)
	B.append(b)
	C.append(c)
	a_sum+=a
	b_sum+=b

dp=[ [ [ float("inf") for y in range(b_sum+1) ] for x in range(a_sum+1)] for k in range(N+1) ]
dp[0][0][0]=0


for k in range(1,N+1):
	for x in range(a_sum+1):
		for y in range(b_sum+1):
			dp[k][x][y]=min( dp[k][x][y], dp[k-1][x][y] )
			if x-A[k-1]>=0 and y-B[k-1]>=0:
				dp[k][x][y]=min( dp[k-1][x][y], dp[k-1][x-A[k-1]][y-B[k-1]]+C[k-1] )


ans=float("inf")
for x in range(1,a_sum+1):
	for y in range(1,b_sum+1):
		if x*Mb==y*Ma:
			ans=min(ans,dp[N][x][y])

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

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict
N,Ma,Mb=map(int,raw_input().split())
item=[]
i_sum=0
for i in range(N):
	a,b,c=map(int,raw_input().split())
	i_sum+=c
	item.append( (a,b,c) )

cost=defaultdict(lambda: None)

for i in item:
	x=i[0]
	y=i[1]
	w=i[2]
	if len(cost)==0:
		cost[0]=[(0,0)]
		cost[w]=[(x,y)]
	else:
		for j in cost.items():
			tw=j[0]
			for k in j[1]:
				tx=k[0]
				ty=k[1]
				if cost[tw+w] is None:
					cost[tw+w]=[(x+tx,y+ty)]
				else:
					cost[tw+w]+=[(x+tx,y+ty)]


for i in cost.items():
	w=i[0]
	for x,y in i[1]:
		if x*Mb==y*Ma and x*Mb!=0:
			print w
			quit()
else:
	print -1

Submission status: Time Limit Exceeded

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

S = 411
MAX_N = 10
MAX_SIZE = 400
INF = int(1e9)
dp = [[INF] * S for i in range(S)]
dp[0][0] = 0
for i in range(N):
    for j in range(MAX_SIZE, -1, -1):
        for k in range(MAX_SIZE, -1, -1):
            dp[j+a[i]][k+b[i]] = min((dp[j+a[i]][k+b[i]], dp[j][k] + c[i]))

ans = INF
for i in range(1, MAX_N):
    ans = min((ans, dp[i*Ma][i*Mb]))
if ans == INF:
    print(-1)
else:
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import defaultdict, Counter
from itertools import product, groupby, count, permutations, combinations
from math import pi, sqrt, ceil, floor
from collections import deque
from bisect import bisect, bisect_left, bisect_right
from string import ascii_lowercase
from functools import lru_cache, reduce

INF = float("inf")
sys.setrecursionlimit(10 ** 7)

# 4近傍（右, 下, 左, 上）
dy = [0, -1, 0, 1]
dx = [1, 0, -1, 0]


def inside(y: int, x: int, H: int, W: int) -> bool: return 0 <= y < H and 0 <= x < W


def main():
    N, Ma, Mb = map(int, input().split())
    dp = [[[INF] * 401 for j in range(401)] for i in range(N + 1)]
    dp[0][0][0] = 0
    a_b_c = [map(int, input().split()) for _ in range(N)]

    for i, (a, b, c) in enumerate(a_b_c):
        for j in range(len(dp[0])):
            for k in range(len(dp[0][0])):
                # not use
                dp[i + 1][j][k] = min(dp[i + 1][j][k], dp[i][j][k])

                # use
                if j + a < len(dp[0]) and k + b < len(dp[0][0]):
                    dp[i + 1][j + a][k + b] = min(dp[i + 1][j + a][k + b], dp[i][j][k] + c)

    ans = INF
    for i in count(1):
        a, b = Ma * i, Mb * i
        if a >= len(dp[0]) or b >= len(dp[0][0]):
            break
        ans = min(ans, dp[-1][a][b])
    if ans != INF:
        print(ans)
    else:
        print(-1)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
N,MA,MB = map(int,raw_input().split())
src = []
sum_a = sum_b = 0
for i in range(N):
  a,b,c = map(int,raw_input().split())
  src.append((a,b,c))
  sum_a += a
  sum_b += b

INF = 10**9
dp = [[[INF for b in range(sum_b+1)] for a in range(sum_a+1)] for i in range(N+1)]
dp[0][0][0] = 0

for i in range(N):
  ai,bi,ci = src[i]
  for a in range(sum_a+1 - ai):
    for b in range(sum_b+1 - bi):
      dp[i+1][a][b] = min(dp[i+1][a][b], dp[i][a][b])
      dp[i+1][a+ai][b+bi] = min(dp[i][a+ai][b+bi], dp[i][a][b] + ci)

ans = INF
n = 1
while True:
  a,b = n*MA,n*MB
  if a > sum_a or b > sum_b: break
  ans = min(ans, dp[N][a][b])
  n += 1

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

Submission status: Time Limit Exceeded

Solution code:
N, Ma, Mb = [int(i) for i in input().split()]
medic = [0] * N
for i in range(N):
    medic[i] = [int(i) for i in input().split()]
cost = [[float('inf')] * 401 for _ in range(401)]


def solve(a, b, num, c):
    if num is N:
        return 0
    for i in range(2):
        if i is 0:
            cost[a + medic[num][0]][b + medic[num][1]] = min(cost[a + medic[num][0]][b + medic[num][1]],
                                                             c + medic[num][2])
            solve(a + medic[num][0], b + medic[num][1], num + 1, cost[a + medic[num][0]][b + medic[num][1]])
        else:
            solve(a, b, num + 1, c)

    return 0


solve(0, 0, 0, 0)
ans = float('inf')
for i in range(400 // max(Ma, Mb)):
    ans = min(ans, cost[Ma * i][Mb * i])
if ans > 1000:
    print(-1)
else:
    print(ans)

Submission status: Time Limit Exceeded

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

#iまでの薬品で、aがj(g),bがk(g)となるときの最小コスト
dp = [[[10 ** 15 for i in range(n + 1)] for j in range(401)] \
    for k in range(401)]

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

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

i = 1
ans = 10 ** 15
while True:
    if i * ma > 400 or i * mb > 400:
        break
    ans = min(ans, dp[i * mb][i * ma][n])
    i += 1

if ans == 10 ** 15:
    ans = -1

print(ans)

Submission status: Time Limit Exceeded

Solution code:
import fractions

n, ma, mb = map(int,input().split())
a = [0] * (n + 1)
b = [0] * (n + 1)
c = [0] * (n + 1)
for i in range(1, n + 1):
    a[i], b[i], c[i] = map(int,input().split())

#iまでの薬品で、aがj(g),bがk(g)となるときの最小コスト
dp = [[[float('inf') for i in range(n + 1)] for j in range(401)] \
    for k in range(401)]

dp[0][0][0] = 0
sa = [0] * (n + 1)
sb = [0] * (n + 1)

for i in range(1, n + 1):
    sa[i] = sa[i - 1] + a[i]
    sb[i] = sb[i - 1] + b[i]

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

i = 1
ans = float('inf')
while True:
    if i * ma > 400 or i * mb > 400:
        break
    ans = min(ans, dp[i * mb][i * ma][n])
    i += 1

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

print(ans)

Submission status: Time Limit Exceeded

Solution code:
import fractions

n, ma, mb = map(int,input().split())
a = [0] * (n + 1)
b = [0] * (n + 1)
c = [0] * (n + 1)
for i in range(1, n + 1):
    a[i], b[i], c[i] = map(int,input().split())

#iまでの薬品で、aがj(g),bがk(g)となるときの最小コスト
dp = [[[float('inf') for i in range(n + 1)] for j in range(401)] \
    for k in range(401)]

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

for i in range(1, n + 1):
    for j in range(401):
        for k in range(401):
            # i番目を買うか、買わないか
            if j < a[i] or k < b[i]:
                dp[k][j][i] = dp[k][j][i - 1]
            else:
                dp[k][j][i] = min(dp[k][j][i - 1], \
                    dp[k - b[i]][j - a[i]][i - 1] + c[i])

i = 1
ans = float('inf')
while True:
    if i * ma > 400 or i * mb > 400:
        break
    ans = min(ans, dp[i * mb][i * ma][n])
    i += 1

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

print(ans)

Submission status: Time Limit Exceeded

Solution code:

import numpy as np

if 1:
    n,ma,mb = map(int, input().split(' '))
    abc = [list(map(int, input().split(' '))) for i in range(n)]
elif 0:
    n,ma,mb = 3,1,1
    abc = [[1,2,1],[2,1,2],[3,3,10]]
else:
    n,ma,mb = 1,1,10
    abc = [[10,10,10]]
    

INF = np.int32(10000000)
dp = np.ones((n+1,10*n+1,10*n+1),dtype=np.int32)*INF
dp[0,0,0] = 0

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

i = 1
ret = []
while True:
    try:
        ret.append(dp[-1,i*ma,i*mb])
        i+= 1
    except:
        break
    
ret = min(ret)
if ret == INF:
    ret = -1
print(ret)

Submission status: Time Limit Exceeded

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

dp = [[[4001 for i in range(411)] for j in range(411)] for l in range(N+1)]

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

for i in range(1,N+1):
    for j in range(400):
        for k in range(400):
            dp[i][j+a[i-1]][k+b[i-1]] = min(dp[i-1][j][k] + c[i-1],dp[i-1][j+a[i-1]][k+b[i-1]])
            dp[i][j][k] = min(dp[i - 1][j][k], dp[i][j][k])
s = min(400//Ma,400//Mb)

min = 4001
for i in range(1,s+1):
    x = dp[N][i*Ma][i*Mb]
    if x>0 and min > x:
        min = x

if min != 4001:
    print(min)
else:
    print(-1)

Submission status: Time Limit Exceeded

Solution code:
import sys

def solve():
    N, Ma, Mb = map(int, input().split())
    table = [tuple(map(int, input().split())) for i in range(N)]

    g1 = half_rekkyo(N, Ma, Mb, table, 0, N // 2)
    g2 = half_rekkyo(N, Ma, Mb, table, N // 2, N - N // 2)

    inf = 100 * 40 + 1
    ans = inf

    if 0 in g1:
        ans = min(ans, g1[0])
    if 0 in g2:
        ans = min(ans, g2[0])

    for v1, c1 in g1.items():
        if -v1 in g2:
            tmp = c1 + g2[-v1]
            ans = min(ans, tmp)

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

def half_rekkyo(N, Ma, Mb, table, s, m):
    res = dict()

    for comb in range(1, 2**m):
        v = 0
        cost = 0

        for i in range(m):
            if comb & (1 << i):
                a, b, c = table[s + i]
                v += b * Ma - a * Mb
                cost += c

        if v in res:
            res[v] = min(res[v], cost)
        else:
            res[v] = cost

    return res

def debug(x, table):
    for name, val in table.items():
        if x is val:
            print('DEBUG:{} -> {}'.format(name, val), file=sys.stderr)
            return None


if __name__ == '__main__':
    solve()

Submission status: Time Limit Exceeded

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

def dvector(vector):
    global Ma
    global Mb
    global Nlist
    global minicost
    if len(vector) == len(Nlist):
        return 0
    vector.append(1)
    Masum = 0
    Mbsum = 0
    cost = 0
    for i in range(len(vector)):
        Masum+= vector[i] * Nlist[i][0]
        Mbsum+= vector[i] * Nlist[i][1]
        cost += vector[i] * Nlist[i][2]
        if Mbsum > 0:
            if Masum/Mbsum == Ma/Mb:
                if minicost > cost:
                    minicost = cost
        if cost < minicost:
            dvector(vector)
    vector.pop()
    vector.append(0)
    dvector(vector)
    vector.pop()
    return 0
    
dvector([])
if minicost == 10000000:
    print("-1")
else:
    print(minicost)

Submission status: Time Limit Exceeded

Solution code:
# coding: utf-8

N, Ma, Mb = list(map(int, input().split()))
inlist = []
for i in range(N):
	inlist.append(list(map(int, input().split())))

min = float("inf")
for i in range(1, 2**N):
	#print("i: ", i, "\tcombination: ", format(i, '04b'))
	add_a = 0
	add_b = 0
	add_c = 0
	for j in range(N):
		#print("\t", inlist[j][0] * ((i >> j) & 0b1), \
		#inlist[j][1] * ((i >> j) & 0b1), inlist[j][2] * ((i >> j) & 0b1))
		add_a += inlist[j][0] * ((i >> j) & 0b1)
		add_b += inlist[j][1] * ((i >> j) & 0b1)
		add_c += inlist[j][2] * ((i >> j) & 0b1)
	#print("\t-------")
	#print("\t", add_a, add_b, add_c)
	if add_a * Mb == add_b * Ma:
		#print("\t\tIt is equal to the ratio, cost:", add_c)
		if add_c < min:
			min = add_c

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

Submission status: Time Limit Exceeded

Solution code:
n, ma, mb = map(int, raw_input().split())
abc = []
suma = 1
sumb = 1

for i in range(n):
    a,b,c = map(int, raw_input().split())
    suma += a
    sumb += b
    abc.append((a,b,c))

dp = [ [ [float('inf')] * sumb for j in range(suma)] for i in range(n+1)]
for i in range(n+1):
    dp[i][0][0] = 0

# for i in range(n):
#     a,b,c = abc[i]
#     for ai in range(suma):
#         for bi in range(sumb):
#             if ai - a >= 0 and bi - b >= 0:
#                 dp[i+1][ai][bi] = min(dp[i][ai][bi], dp[i+1][ai][bi], dp[i][ai-a][bi-b]+c)

for i in range(n):
    a,b,c = abc[i]
    for ai in range(suma-a):
        for bi in range(sumb-b):
            dp[i+1][ai][bi] = min(dp[i+1][ai][bi], dp[i][ai][bi])
            dp[i+1][ai+a][bi+b] = min(dp[i+1][ai+a][bi+b], dp[i][ai][bi]+c)

ans = float('inf')
i = 1
while i*ma < suma and i*mb < sumb:
    ans = min(ans, dp[n][i*ma][i*mb])
    i += 1

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

Submission status: Time Limit Exceeded

Solution code:
import sys

# read in number of chemical packages n, ratio of A ma, and ratio of B mb
n, ma, mb = map(int, raw_input().split())

# read in contents and cost of n chemical packages
pac = []
for i in range(n):
	pac.append(map(int, raw_input().split()))

def reduce(a,b):
	x = a/ma
	y = b/mb
	z = x if x < y else y
	return [a-z*ma, b-z*mb]

def minCost(a,b,index,cost):
	if a == 0 and b == 0:
		return cost

	if index >= n:
		return sys.maxint

	a_p, b_p = reduce(a+pac[index][0], b+pac[index][1])
	costWith = minCost(a_p,b_p,index+1,cost+pac[index][2])
	costWithout = minCost(a,b,index+1,cost)

	return min(costWith, costWithout)

temp = minCost(ma, mb, 0, 0)
if temp == sys.maxint:
	print (-1)
else:
	print (temp)

Submission status: Time Limit Exceeded

Solution code:
import sys
inf = float('inf')

def debug(x, table):
    for name, val in table.items():
        if x is val:
            print('DEBUG:{} -> {}'.format(name, val), file=sys.stderr)
            return None

def solve():
    N, Ma, Mb = map(int, input().split())
    a_w = []
    b_w = []
    costs = []

    for i in range(N):
        a, b, c = map(int, input().split())
        a_w.append(a)
        b_w.append(b)
        costs.append(c)

    dp = [[[inf]*(10*N + 1) for j in range(10*N + 1)]
            for k in range(2)]

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

    for i in range(N):
        for a in range(10*N + 1):
            for b in range(10*N + 1):
                dp[1][a][b] = dp[0][a][b]
                if a - a_w[i] >= 0 and b - b_w[i] >= 0:
                    dp[1][a][b] = min(dp[1][a][b],
                                      dp[0][a - a_w[i]][b - b_w[i]] + costs[i])
        
        for k in range(10*N + 1):
            dp[0][k] = dp[1][k][:]

    min_cost = inf

    for a in range(1, 10*N + 1):
        for b in range(1, 10*N + 1):
            if a * Mb == b * Ma:
                min_cost = min(min_cost, dp[1][a][b])

    if min_cost == inf:
        ans = -1
    else:
        ans = min_cost

    print(ans)


if __name__ == '__main__':
    solve()

Submission status: Time Limit Exceeded

Solution code:
import sys
inf = float('inf')

def debug(x, table):
    for name, val in table.items():
        if x is val:
            print('DEBUG:{} -> {}'.format(name, val), file=sys.stderr)
            return None

def solve():
    N, Ma, Mb = map(int, input().split())
    wa = [None]
    wb = [None]
    costs = [None]

    for i in range(N):
        a, b, c = map(int, input().split())
        wa.append(a)
        wb.append(b)
        costs.append(c)

    dp = [[[inf]*(10*N + 1) for j in range(10*N + 1)]
                           for k in range(N + 1)]

    # debug(dp, locals())
    dp[0][0][0] = 0

    for k in range(1, N + 1):
        for a in range(10*N + 1):
            for b in range(10*N + 1):
                dp[k][a][b] = dp[k - 1][a][b]
                if a - wa[k] >= 0 and b - wb[k] >= 0:
                    dp[k][a][b] = min(dp[k][a][b],
                                        dp[k - 1][a - wa[k]][b - wb[k]] + costs[k])

    min_c = inf

    for a in range(1, 10*N + 1):
        for b in range(1, 10*N + 1):
            if a * Mb == b * Ma:
                min_c = min(min_c, dp[N][a][b])

    if min_c == inf:
        ans = -1
    else:
        ans = min_c

    print(ans)

if __name__ == '__main__':
    solve()