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: Wrong Answer

Solution code:
import sys

sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))

# 行列のDPを持つ　縦軸がa
N, Ma, Mb = lr()
INF = 5000
limit = N * 10 + 1
dp = [[INF] * limit for _ in range(limit)]
dp[0][0] = 0
for _ in range(N):
    a, b, c = lr()
    for i in range(limit):
        if i < a:
            continue
        for j in range(limit):
            if j < b:
                continue
            dp[i][j] = min(dp[i][j], dp[i-a][j-b] + c)

answer = INF
for i in range(1, limit):
    if i % Ma != 0:
        continue
    for j in range(1, limit):
        if j % Mb != 0:
            continue
        if i // Ma == j // Mb:
            if dp[i][j] < answer:
                answer = dp[i][j]

print(answer if answer != INF else -1)
# 10

Submission status: Wrong Answer

Solution code:
# 半分全列挙バージョン
import sys

sys.setrecursionlimit(10 ** 6)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep="\n")
def II(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def SI(): return sys.stdin.readline()[:-1]

def allptn(abc,ma,mb):
    inf=10**9
    # a,b,cの全組合せを作る
    allabc=[(0,0,0)]
    for a,b,c in abc:
        n=len(allabc)
        for i in range(n):
            aa,bb,cc=allabc[i]
            allabc.append((aa+a,bb+b,cc+c))
    # 指標とコストの組合せにする
    # 指標が重複するときはコストが小さいほうだけ残す
    # 指標が0のときは前後半で組み合わせる必要がないので単独で答えを出しておく
    vc={}
    ans=inf
    for a,b,c in allabc[1:]:
        val=a*mb-b*ma
        if val:
            pc=vc.setdefault(val,inf)
            if c<pc:vc[val]=c
        else:
            if c<ans:ans=c
    res=[(val,c) for val,c in sorted(vc.items())]
    return ans,res

def main():
    n,ma,mb=MI()
    abc=[LI() for _ in range(n)]
    inf=10**9
    # 前半の要素をa1,b1、後半の要素をa2,b2とする
    # (a1+a2):(b1+b2)=ma:mbとなればよい。式変形すると
    # (mb*a1-ma*b1)+(mb*a2-ma*b2)=0となる
    # つまり各要素についてmb*a-ma*bという指標を計算し、前半と後半で和が0になる組合せを探せばよい
    # 前半全列挙
    ans,pre=allptn(abc[:n//2],ma,mb)
    # 後半全列挙
    ret,pos=allptn(abc[n//2:],ma,mb)
    ans=min(ans,ret)
    # 指標が昇順になるよう並び替えて、前半は前から後半は後からしゃくとり法で
    # 指標の和が0になるところのコストを求める
    j=len(pos)-1
    ans=inf
    for val,c in pre:
        while val+pos[j][0]>0 and j:j-=1
        if val+pos[j][0]==0:ans=min(ans,c+pos[j][1])
    if ans==inf:print(-1)
    else:print(ans)

main()

Submission status: Wrong Answer

Solution code:
# 半分全列挙バージョン
import sys

sys.setrecursionlimit(10 ** 6)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep="\n")
def II(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def SI(): return sys.stdin.readline()[:-1]

def allptn(abc,ma,mb):
    inf=10**9
    # a,b,cの全組合せを作る
    allabc=[(0,0,0)]
    for a,b,c in abc:
        n=len(allabc)
        for i in range(n):
            aa,bb,cc=allabc[i]
            allabc.append((aa+a,bb+b,cc+c))
    # 指標とコストの組合せにする
    # 指標が重複するときはコストが小さいほうだけ残す
    # 指標が0のときは前後半で組み合わせる必要がないので単独で答えを出しておく
    vc={}
    ans=inf
    for a,b,c in allabc[1:]:
        val=a*mb-b*ma
        if val:
            pc=vc.setdefault(val,10**9)
            if c<pc:vc[val]=c
        else:
            if c<ans:ans=c
    res=[(val,c) for val,c in sorted(vc.items())]
    return ans,res

def main():
    n,ma,mb=MI()
    abc=[LI() for _ in range(n)]
    inf=10**9
    # 前半の要素をa1,b1、後半の要素をa2,b2とする
    # (a1+a2):(b1+b2)=ma:mbとなればよい。式変形すると
    # (mb*a1-ma*b1)+(mb*a2-ma*b2)=0となる
    # つまり各要素についてmb*a-ma*bという指標を計算し、前半と後半で和が0になる組合せを探せばよい
    # 前半全列挙
    ans,pre=allptn(abc[:n//2],ma,mb)
    # 後半全列挙
    ret,pos=allptn(abc[n//2:],ma,mb)
    ans=min(ans,ret)
    # 指標が昇順になるよう並び替えて、前半は前から後半は後からしゃくとり法で
    # 指標の和が0になるところのコストを求める
    j=len(pos)-1
    ans=inf
    for val,c in pre:
        while val+pos[j][0]>0 and j>0:j-=1
        while val+pos[j][0]==0 and j>=0:
            now=c+pos[j][1]
            if now<ans:ans=now
            j-=1
        if j<0:break
    if ans==inf:print(-1)
    else:print(ans)

main()

Submission status: Wrong Answer

Solution code:
# 半分全列挙バージョン
import sys

sys.setrecursionlimit(10 ** 6)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep="\n")
def II(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def SI(): return sys.stdin.readline()[:-1]

def main():
    n,ma,mb=MI()
    abc=[LI() for _ in range(n)]
    inf=10**9
    # 前半の要素をa1,b1、後半の要素をa2,b2とする
    # (a1+a2):(b1+b2)=ma:mbとなればよい。式変形すると
    # (mb*a1-ma*b1)+(mb*a2-ma*b2)=0となる
    # つまり各要素についてmb*a-ma*bという指標を計算し、前半と後半で和が0になる組合せを探せばよい
    # 前半全列挙
    pre=[(0,0,0)]
    for a,b,c in abc[:n//2]:
        pn=len(pre)
        for i in range(pn):
            pa,pb,pc=pre[i]
            pre.append((a+pa,b+pb,c+pc))
    pre=[(a*mb-b*ma,c) for a,b,c in pre]
    # 後半全列挙
    pos=[(0,0,0)]
    for a,b,c in abc[n//2:]:
        pn=len(pos)
        for i in range(pn):
            pa,pb,pc=pos[i]
            pos.append((a+pa,b+pb,c+pc))
    pos=[(a*mb-b*ma,c) for a,b,c in pos]
    # 指標が昇順になるよう並び替えて、前半は前から後半は後からしゃくとり法で
    # 指標の和が0になるところのコストを求める
    pre.sort()
    pos.sort()
    j=len(pos)-1
    ans=inf
    for val,c in pre:
        while val+pos[j][0]>0 and j>0:j-=1
        while val+pos[j][0]==0 and j>=0:
            now=c+pos[j][1]
            if now and now<ans:ans=now
            j-=1
        if j<0:break
    if ans==inf:print(-1)
    else:print(ans)

main()

Submission status: Wrong Answer

Solution code:
# 半分全列挙バージョン
import sys

sys.setrecursionlimit(10 ** 6)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep="\n")
def II(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def SI(): return sys.stdin.readline()[:-1]

def main():
    n,ma,mb=MI()
    abc=[LI() for _ in range(n)]
    inf=10**9
    # 前半の要素をa1,b1、後半の要素をa2,b2とする
    # (a1+a2):(b1+b2)=ma:mbとなればよい。式変形すると
    # (mb*a1-ma*b1)+(mb*a2-ma*b2)=0となる
    # つまり各要素についてmb*a-ma*bという指標を計算し、前半と後半で和が0になる組合せを探せばよい
    # 前半全列挙
    pre=[(0,0,0)]
    for a,b,c in abc[:n//2]:
        add=[]
        for pa,pb,pc in pre:
            add.append((a+pa,b+pb,c+pc))
        pre+=add
    pre=[(a*mb-b*ma,c) for a,b,c in pre]
    # 後半全列挙
    pos=[(0,0,0)]
    for a,b,c in abc[n//2:]:
        add=[]
        for pa,pb,pc in pos:
            add.append((a+pa,b+pb,c+pc))
        pos+=add
    pos=[(a*mb-b*ma,c) for a,b,c in pos]
    # 指標が昇順になるよう並び替えて、前半は前から後半は後からしゃくとり法で
    # 指標の和が0になるところのコストを求める
    pre.sort()
    pos.sort()
    j=len(pos)-1
    ans=inf
    for val,c in pre:
        while val+pos[j][0]>0 and j>0:j-=1
        while val+pos[j][0]==0 and j>=0:
            now=c+pos[j][1]
            if now and now<ans:ans=now
            j-=1
        if j<0:break
    if ans==inf:print(-1)
    else:print(ans)

main()

Submission status: Wrong Answer

Solution code:
import sys, bisect, math, itertools, string, queue, copy
# import numpy as np
# import scipy
from collections import Counter,defaultdict,deque
from itertools import permutations, combinations
from heapq import heappop, heappush
input = sys.stdin.readline
sys.setrecursionlimit(10**8)
mod = 10**9+7
def inp(): return int(input()) # n=1
def inpm(): return map(int,input().split()) # x=1,y=2
def inpl(): return list(map(int, input().split())) # a=[1,2,3,4,5,...,n]
def inpls(): return list(input().split())  # a=['1','2','3',...,'n']
def inplm(n): return list(int(input()) for _ in range(n)) # x=[] 複数行
def inplL(n): return [list(input()) for _ in range(n)]
def inplT(n): return [tuple(input()) for _ in range(n)]
def inpll(n): return [list(map(int, input().split())) for _ in range(n)] # [[2,2,2,2],[1,1,1,1],[3,3,3,3]] 
def inplls(n): return sorted([list(map(int, input().split())) for _ in range(n)]) # [[1,1,1,1],[2,2,2,2],[3,3,3,3]] 

def gcd(a, b): #最大公約数
    if b == 0:
        return a
    else:
        return gcd(b, a%b)

def main():
    n,Ma,Mb = inpm()
    LOW = []
    HIGH = []
    SAME = []
    rate = Ma/Mb
    for _ in range(n):
        a,b,c = inpm()
        r = a/b
        if r < rate:
            LOW.append((a,b,c))
        elif r > rate:
            HIGH.append((a,b,c))
        else:
            SAME.append((a,b,c))
    if SAME != []:
        ans = 10**10
        for e in SAME:
            cost = e[2]
            ans = min(ans,cost)
    if LOW == [] or HIGH == []:
        print(-1)
        return
    ans = 10**10
    for e in LOW:
        for f in HIGH:
            [a1,b1,c1] = e
            [a2,b2,c2] = f
            n = abs(b*a2-a*b2)
            m = abs(a*b1-b*a1)
            x = gcd(n,m)
            n //= x
            m //= x
            cost = c1*n + c2*m
            ans = min(ans,cost)
    print(ans)
    
if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
ab=[[float('inf') for j in range(401)] for i in range(401)]
n,ma,mb=map(int,input().split())
a,b,c=map(int,input().split())
ab[a][b]=c
for i in range(n-1):
    a,b,c=map(int,input().split())
    for j in range(400,-1,-1):
        for k in range(400,-1,-1):
            if ab[j][k]!=float('inf'):
                ab[j+a][k+b]=min(ab[j][k]+c,ab[j+a][k+b])
ans=float('inf')
a,b=ma,mb
while a<401 and b<401:
    ans=min(ans,ab[a][b])
    a+=ma
    b+=mb
if ans==float('inf'):
    ans=-1
print(ans)

Submission status: Wrong Answer

Solution code:
from itertools import permutations
n,ma, mb = map(int, input().split())
abc = []
inf = float('INF')
hw = 400 + 1
dp = [[inf for i in range(hw)] for j in range(hw)]
dp[0][0] = 0
for _ in range(n):
    a,b,c = map(int, input().split())
    abc.append((a,b,c))

abc.sort(key = lambda x:(-x[0],x[1]))
for a,b,c in abc:
    for i in range(hw-a):
        for j in range(hw-b):
            if dp[i+a][j+b] > dp[i][j] + c:
                dp[i+a][j+b] = dp[i][j] + c

abc.sort(key = lambda x:(-x[1],x[0]))
for a,b,c in abc:
    for i in range(hw-a):
        for j in range(hw-b):
            if dp[i+a][j+b] > dp[i][j] + c:
                dp[i+a][j+b] = dp[i][j] + c

a,b = ma, mb
ans = [dp[a*i][b*i] for i in range(1,hw // max(a,b)) if dp[a*i][b*i] < inf]
print(min(ans) if len(ans) else -1)
# [print(i, f) for i,f in enumerate(dp[200:])]
# print(ans)

Submission status: Wrong Answer

Solution code:
from itertools import permutations
n,ma, mb = map(int, input().split())
abc = []
inf = float('INF')
hw = 400 + 1
dp = [[inf for i in range(hw)] for j in range(hw)]
dp[0][0] = 0
for _ in range(n):
    a,b,c = map(int, input().split())
    abc.append((a,b,c))

abc.sort(key = lambda x:x[0])
for a,b,c in abc:
    for i in range(hw-a):
        for j in range(hw-b):
            if dp[i+a][j+b] > dp[i][j] + c:
                dp[i+a][j+b] = dp[i][j] + c

abc.sort(key = lambda x:x[1])
for a,b,c in abc:
    for i in range(hw-a):
        for j in range(hw-b):
            if dp[i+a][j+b] > dp[i][j] + c:
                dp[i+a][j+b] = dp[i][j] + c

a,b = ma, mb
ans = [dp[a*i][b*i] for i in range(1,hw // max(a,b)) if dp[a*i][b*i] < inf]
print(min(ans) if len(ans) else -1)
# [print(i, f) for i,f in enumerate(dp[200:])]
# print(ans)

Submission status: Wrong Answer

Solution code:
from itertools import permutations
n,ma, mb = map(int, input().split())
abc = []
inf = float('INF')
dp = [[inf for i in range(401)] for j in range(401)]
dp[0][0] = 0
for _ in range(n):
    a,b,c = map(int, input().split())
    abc.append((a,b,c))
    mn = max(a,b)
    for i in range(401-a):
        for j in range(401-b):
            if dp[i+a][j+b] > dp[i][j] + c:
                dp[i+a][j+b] = dp[i][j] + c
ans = inf
flag = False
a,b = ma, mb
while a < 401 and b < 401:
    if ans > dp[a][b]:
        ans = dp[a][b]
        flag = True
    a += ma
    b += mb

print(ans if flag else -1)
# [print(i) for i in dp]

Submission status: Wrong Answer

Solution code:
n,ma,mb=map(int,input().split())
dpn=400001
dp=[10**6]*dpn
dp[0]=0
for i in range(n):
    a,b,c=map(int,input().split())
    for j in range(dpn-1,-1,-1):
        if j==0 or dp[j]!=10**6:
            dp[j+a*1000+b]=min(dp[j+a*1000+b],dp[j]+c)
ans=10**6
s=1000*ma+mb
p=1
while s*p<dpn:
    ans=min(ans,dp[s*p])
    p+=1
print(ans)

Submission status: Wrong Answer

Solution code:
n,ma,mb=map(int,input().split())
dpn=10**6
dp=[10**6]*dpn
dp[0]=0
for i in range(n):
    a,b,c=map(int,input().split())
    for j in range(dpn-1,-1,-1):
        if j==0 or dp[j]!=10**6:
            dp[j+a*1000+b]=min(dp[j+a*1000+b],dp[j]+c)
ans=10**6
s=1000*ma+mb
p=1
while s*p<10**6:
    ans=min(ans,dp[s*p])
    p+=1
print(ans)

Submission status: Wrong Answer

Solution code:
import numpy as np

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

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

items = np.array(items)

import itertools
l = list(itertools.product([False,True], repeat=N))

min_cost = 1000000000000000000
for comb in l[1:]:
  idx = np.where(comb)
  cost = items[idx,2].sum()
  if (items[idx,0].sum() == Ma) & (items[idx,1].sum() == Mb) & (cost < min_cost):
    min_cost = cost
if min_cost == 1000000000000000000:
  print("-1")
else:
  print(min_cost)

Submission status: Wrong Answer

Solution code:
import numpy as np

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

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

items = np.array(items)

import itertools
l = list(itertools.product([False,True], repeat=N))

min_cost = 1000000000000000000
for comb in l[1:]:
  idx = np.where(comb)
  cost = items[idx,2].sum()
  if (items[idx,0].sum() == items[idx,1].sum()) & (cost < min_cost):
    min_cost = cost
if min_cost == 1000000000000000000:
  print("-1")
else:
  print(min_cost)

Submission status: Wrong Answer

Solution code:
import numpy as np

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

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

items = np.array(items)

import itertools
l = list(itertools.product([False,True], repeat=N))

min_cost = 1000000000000000000
for comb in l[1:]:
  idx = np.where(comb)
  cost = items[idx,2].sum()
  if (items[idx,0].sum() == items[idx,1].sum()) & (cost < min_cost):
    min_cost = cost
print(int(min_cost))

Submission status: Wrong Answer

Solution code:
import numpy as np

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

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

items = np.array(items)

import itertools
l = list(itertools.product([False,True], repeat=N))

min_cost = 1000000000000000000
for comb in l[1:]:
  idx = np.where(comb)
  cost = items[idx,2].sum()
  if (items[idx,0].sum() == items[idx,1].sum()) & (cost < min_cost):
    min_cost = cost
print(min_cost)

Submission status: Wrong Answer

Solution code:
cost_lst = [''] * 20000

'''
N : 0,1,2,3,4,5,6...
n : 0,1,-1,2,-2,3,-3...
'''
def N_n(N):
	return int((-1)**((N%2) + 1) * (N + (N%2))/2)

def n_N(n):
	if n <= 0:
		return int((-2) * n)
	else:
		return int(2 * n - 1)

def UPDATE(n,c):
	N = n_N(n)
	if cost_lst[N] == '':
		cost_lst[N] = c
	elif cost_lst[N] > c:
		cost_lst[N] = c

	return 0

if __name__ == '__main__':
	num, Ma, Mb = map(int, input().split())
	drug_lst = []
	for i in range(0,num):
		drug_lst.append([int(p) for p in input().split()])

	value_list = []

	for i in range(0,num):
		v = drug_lst[i][0] * Mb - drug_lst[i][1] * Ma
		value_list.append([v,drug_lst[i][2]])

	for l in value_list:
		n, c = l[0], l[1]
		UPDATE(n,c)
		for i in range(0,10000):
			if cost_lst[i] != '':
				cc = c + cost_lst[i]
				nn = n + N_n(i)
				UPDATE(nn,cc)

	if cost_lst[0] == '':
		print(-1)
	else:
		print(cost_lst[0])

Submission status: Wrong Answer

Solution code:
cost_lst = [''] * 100000

def N_n(N):
	return int((-1)**(N%2 + 1) * (N + N%2)/2)

def n_N(n):
	if n <= 0:
		return int((-2) * n)
	else:
		return int(2 * n - 1)

def UPDATE(n,c):
	N = n_N(n)
	if cost_lst[N] == '':
		cost_lst[N] = c
	elif cost_lst[N] > c:
		cost_lst[N] = c

	return 0

if __name__ == '__main__':
	N, Ma, Mb = map(int, input().split())
	drug_lst = []
	for i in range(0,N):
		drug_lst.append([int(p) for p in input().split()])

	value_list = []

	for i in range(0,N):
		v = drug_lst[i][0] * Mb - drug_lst[i][1] * Ma
		value_list.append([v,drug_lst[i][2]])

	for l in value_list:
		n, c = l[0], l[1]
		UPDATE(n,c)
		for i in range(0,10000):
			if cost_lst[i] != '':
				cc = c + cost_lst[i]
				nn = n + N_n(i)
				UPDATE(nn,cc)

	if cost_lst[0] == '':
		print(-1)
	else:
		print(cost_lst[0])

Submission status: Wrong Answer

Solution code:
def args():
    N, MA, MB = list(map(int, input().split()))

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

    # print(N, MA, MB)
    # print(A)
    # print(B)
    # print(C)

    return N, MA, MB, A, B, C


def solve(N, MA, MB, A, B, C):
    def recur(i, a, b, cost):
        if not i < N:
            if 0 < a and 0 < b:
                m = min(a, b)
                if (MA, MB) == (a / m, b / m):
                    return cost
            return float("inf")

        return min(recur(i + 1, a, b, cost), recur(i + 1, a + A[i], b + B[i], cost + C[i]))

    ans = recur(0, 0, 0, 0)

    return ans


if __name__ == '__main__':
    res = solve(*args())

    print(-1) if res == float("inf") else print(res)

Submission status: Wrong Answer

Solution code:
N,Ma,Mb = map(int,input().split())
dp = [[[10**9 for i in range(401)] for j in range(401)] for k in range(N+1)]
dp[0][0][0] = 0
for i in range(1,N+1):
    a,b,c = map(int,input().split())
    for j in range(401):
        for k in range(401):
            if j < a:
                dp[i][j][k] = dp[i-1][j][k]
            else:
                if k < b:
                    dp[i][j][k] = dp[i-1][j][k]
                else:
                    dp[i][j][k] = min(dp[i-1][j][k],dp[i-1][j-a][k-b] + c)
m = max(Ma,Mb)
import math
n = math.floor(400 / m)
ans = 10**9
for i in range(1,n):
    x = Ma*i
    y = Mb*i
    ans = min(dp[N][x][y],ans)
print(ans)

Submission status: Wrong Answer

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


ANS=[[[-1 for k in range(401)] for j in range(401)] for i in range(41)]




INF=1000000000000000000000

def f(ind,wa,wb):
	global Ma
	global Mb
	global N
	if ANS[ind][wa][wb]==-1:
		if ind==0:
			if (wa+A[0])*Mb==(wb+B[0])*Ma:
				ANS[ind][wa][wb] = C[0]
			else:
				ANS[ind][wa][wb] = INF
		else:
			ANS[ind][wa][wb] = min(f(ind-1,wa,wb),f(ind-1,wa+A[ind],wb+B[ind])+C[ind])
	return ANS[ind][wa][wb]

ans=f(N-1,0,0)

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

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
#
N, Ma, Mb = map(int, input().split(' '))
a_b_c_list = [list(map(int, input().split(' '))) for _ in range(N)]

lim = 101
get_row = lambda : [[float('inf') for _ in range(lim)] for _ in range(lim)]
table = [get_row()]
for _ in range(N):
    table.append(get_row())
table[0][0][0] = 0

for i, (a, b, c) in enumerate(a_b_c_list):
    for j in range(lim):
        for k in range(lim):
            if table[i][j][k] != float('inf'):
                table[i+1][j][k] = table[i][j][k]
                if j+a <= 100 and k+b <= 100:
                    table[i+1][j+a][k+b] = min(table[i][j+a][k+b], table[i][j][k] + c)

# for i in range(lim):
#     print(*table[N][i])

ans = float('inf')
for i in range(1, lim//max(Ma, Mb)+1):
    a, b = i * Ma, i * Mb
    if a < lim and b < lim and table[N][a][b] != float('inf'):
        # print(a, b, table[N][a][b])
        ans = min(ans, table[N][a][b])

if ans == float('inf'):
    print(-1)
else:
    print(ans)
# for t in table:
#     print(*t)

Submission status: Wrong Answer

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

lim = 101
table = [[float('inf') for _ in range(lim)] for _ in range(lim)]
table[0][0] = 0

for a, b, c in a_b_c_list:
    for i in range(100-a):
        for j in range(100-b):
            if table[i][j] != float('inf'):
                table[i+a][j+b] = min(table[i+a][j+b], table[i][j] + c)

ans = float('inf')
for i in range(1, lim//max(Ma, Mb)+1):
    a, b = i * Ma, i * Mb
    if a < lim and b < lim and table[a][b] != float('inf'):
        # print(a, b, table[a][b])
        ans = min(ans, table[a][b])

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

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
n,ma,mb=map(int,input().split())
dp=[[[float("inf")]*500 for _ in range(500)] for i 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(450):
        for k in range(450):
            dp[i+1][j][k]=dp[i][j][k]
            dp[i+1][j+a][k+b]=min(dp[i+1][j+a][k+b],dp[i][j][k]+c)
ans=float("inf")
i=1
#print(dp[-1])
while i*ma<450 and i*mb<450:
    ans=min(ans,dp[-1][ma*i][mb*i])
    i+=1
print(ans if ans!=float("inf") else -1)

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
n,ma,mb=map(int,input().split())
dp=[[[float("inf")]*1000 for _ in range(1000)] for i 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(950):
        for k in range(950):
            dp[i+1][j+a][k+b]=min(dp[i][j+a][k+b],dp[i][j][k]+c)
ans=float("inf")
i=1
#print(dp[-1])
while i*ma<950 and i*mb<950:
    ans=min(ans,dp[-1][ma*i][mb*i])
    i+=1
print(ans if ans!=float("inf") else -1)

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
n,ma,mb=map(int,input().split())
dp=[[[float("inf")]*500 for _ in range(500)] for i 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(450):
        for k in range(450):
            dp[i+1][j+a][k+b]=min(dp[i][j+a][k+b],dp[i][j][k]+c)
ans=float("inf")
i=1
#print(dp[-1])
while i*ma<450 and i*mb<450:
    ans=min(ans,dp[-1][ma*i][mb*i])
    i+=1
print(ans if ans!=float("inf") else -1)

Submission status: Wrong Answer

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

A, B = 0, 0
for a, b, _ in items:
    A += a
    B += b

dp = [[[float("inf")] * (B + 1) for _ in range(A + 1)] for _ in range(N + 1)]
for i in range(N + 1):
    dp[i][0][0] = 0

for i in range(N):
    a, b, c = items[i]
    for j in range(A + 1):
        if j - a < 0:
            continue
        for k in range(B + 1):
            if k - b < 0:
                continue
            dp[i + 1][j][k] = min(dp[i][j - a][k - b] + c, dp[i][j][k])

ans = float("inf")
for x in range(1, min(A // Ma, B // Mb) + 1):
    a = Ma * x
    b = Mb * x
    ans = min(dp[N][a][b], ans)

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

Submission status: Wrong Answer

Solution code:
N, A, B = map(int, input().split())

items = []
A_MAX = 0
B_MAX = 0
MAX_cost = 0
for _ in range(N):
    a, b, cost = map(int, input().split())
    items.append((a, b, cost))
    A_MAX += a
    B_MAX += b
    MAX_cost += cost
A_MAX = 400
B_MAX = 400

dp = [[float('infinity')] * (A_MAX + 1) for _ in range(B_MAX + 1)]

dp[0][0] = 0
for a, b, cost in items:
    dp[b][a] = cost

for a, b, cost in items:
    for i in range(1, B_MAX + 1):
        for j in range(1, A_MAX + 1):
            if j - a >= 0 and i - b >= 0:
                dp[i][j] = min(dp[i][j], dp[i - b][j - a] + cost)

ans = float('infinity')
for k in range(1, B_MAX + 1):
    for l in range(1, A_MAX + 1):
        if dp[k][l] == float('infinity'):
            continue
        if A * k > 400 or B * l > 400:
            break
        if A * dp[k] == dp[l] * B:
            ans = min(ans, dp[k][l])
if ans == float('infinity'):
    print(-1)
else:
    print(ans)

Submission status: Wrong Answer

Solution code:
N, A, B = map(int, input().split())

items = []
A_MAX = 0
B_MAX = 0
MAX_cost = 0
for _ in range(N):
    a, b, cost = map(int, input().split())
    items.append((a, b, cost))
    A_MAX += a
    B_MAX += b
    MAX_cost += cost

A_MAX = 400
B_MAX = 400
dp = [[float('infinity')] * (A_MAX + 1) for _ in range(B_MAX + 1)]

dp[0][0] = 0
for a, b, cost in items:
    dp[b][a] = cost

for a, b, cost in items:
    for i in range(1, B_MAX + 1):
        for j in range(1, A_MAX + 1):
            if j - a > 0 and i - b > 0:
                dp[i][j] = min(dp[i][j], dp[i - b][j - a] + cost)

ans = float('infinity')
for k in range(1, B_MAX + 1):
    for l in range(1, A_MAX + 1):
        if dp[k][l] == float('infinity'):
            continue
        if A * dp[k] == dp[l] * B:
            ans = min(ans, dp[k][l])
if ans == float('infinity'):
    print(-1)
else:
    print(ans)

Submission status: Wrong Answer

Solution code:
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
import math
import bisect
import random
from itertools import permutations, accumulate, combinations, product
import sys
from pprint import pprint
from copy import deepcopy
import string
from bisect import bisect_left, bisect_right
from math import factorial, ceil, floor
from operator import mul
from functools import reduce
from pprint import pprint


sys.setrecursionlimit(2147483647)
INF = 10 ** 13
def LI(): return list(map(int, sys.stdin.buffer.readline().split()))
def I(): return int(sys.stdin.buffer.readline())
def LS(): return sys.stdin.buffer.readline().rstrip().decode('utf-8').split()
def S(): return sys.stdin.buffer.readline().rstrip().decode('utf-8')
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): return [S() for i in range(n)]
def LSR(n): return [LS() for i in range(n)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]
mod = 100000000


def gcd(i, j):
    while j:
        i, j = j, i % j
    return i


n, a_ratio, b_ratio = LI()
solution = LIR(n)
dp = {(0, 0): 0}
for a, b, c in solution:
    for (ai, bi), ci in list(dp.items()):
        # listにしないとduring iteration dictionary changeみたいなerrorでる。
        # メモ：defaultdictはもともと存在しないkeyを参照するだけでkey:valueが追加される。
        # これによって、key: INFが追加されるのはまずい。だからgetで
        aj = ai + a; bj = bi + b; cj = ci + c
        g = gcd(aj, bj)
        dp[(aj // g, bj // g)] = min(dp.get((aj // g, bj // g), INF), cj)


print(dp.get((a_ratio, b_ratio), -1))

Submission status: Wrong Answer

Solution code:
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
import math
import bisect
import random
from itertools import permutations, accumulate, combinations, product
import sys
from pprint import pprint
from copy import deepcopy
import string
from bisect import bisect_left, bisect_right
from math import factorial, ceil, floor
from operator import mul
from functools import reduce
from pprint import pprint


sys.setrecursionlimit(2147483647)
INF = 10 ** 13
def LI(): return list(map(int, sys.stdin.buffer.readline().split()))
def I(): return int(sys.stdin.buffer.readline())
def LS(): return sys.stdin.buffer.readline().rstrip().decode('utf-8').split()
def S(): return sys.stdin.buffer.readline().rstrip().decode('utf-8')
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): return [S() for i in range(n)]
def LSR(n): return [LS() for i in range(n)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]
mod = 100000000


def gcd(i, j):
    while j:
        i, j = j, i % j
    return i


n, a_ratio, b_ratio = LI()
solution = LIR(n)
dp = defaultdict(lambda: INF)
dp[(0, 0)] = 0
for a, b, c in solution:
    for (ai, bi), ci in list(dp.items()):
        # listにしないとduring iteration dictionary changeみたいなerrorでる。
        aj = ai + a; bj = bi + b; cj = ci + c
        g = gcd(aj, bj)
        dp[(aj // g, bj // g)] = min(dp[(aj // g, bj // g)], cj)


print(dp[(a_ratio, b_ratio)] if dp[(a_ratio, b_ratio)] != INF else -1)

Submission status: Wrong Answer

Solution code:
import sys
import numpy as np
from copy import deepcopy

I = np.array(sys.stdin.read().split(), dtype=np.int64)
n, ma, mb = I[:3]
a, b, c = I[3:].reshape(n, 3).T

def main():
    sa = np.sum(a)
    sb = np.sum(b)

    res = [[[[0, 0] for _ in range(sb + 1)] for _ in range(sa + 1)] for _ in range(n+1)]
    res[0][0][0][0] = 1
    for i in range(n):
        res[i+1] = deepcopy(res[i])
        for j in range(sa+1):
            for k in range(sb+1):
                if j >= a[i] and k >= b[i]:
                    prev =  res[i][j-a[i]][k-b[i]]
                    if prev[0]:
                        res[i+1][j][k][0] = 1
                        if res[i+1][j][k][1]:
                            res[i+1][j][k][1] = min(prev[1] + c[i], res[i+1][j][k][1])   
                        else:    
                            res[i+1][j][k][1] = prev[1] + c[i]

    for i in range(1, min(sa//ma, sb//mb)+1):
        x = res[n][ma * i][mb * i]
        if x[0]:
            return x[1]
    return -1

if __name__ == '__main__':
    ans = main()
    print(ans)

Submission status: Wrong Answer

Solution code:
N, A, B = map(int, input().split())
X = [1<<20] * 8080
for _ in range(N):
    a, b, c = map(int, input().split())
    t = A*b-B*a
    X = [min(X[i], (0 if i == t else X[(i-t)%8080]) + c) for i in range(8080)]
print(-1 if X[0] > 1<<18 else X[0])