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: Runtime Error

Solution code:
import math

N, Ma, Mb = map(int,input().split())
rate = Ma / Mb
a = [0] * N
b = [0] * N
c = [0] * N
MA = 0
MB = 0
for i in range(N):
    a[i], b[i], c[i] = map(int, input().split())
    MA += a[i]
    MB += b[i]

dp = [[[math.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 it_N in range(N):
    for it_MA in range(MA+1):
        for it_MB in range(MB+1):
            if it_MA >= a[it_N] and it_MB >= b[it_N]:
                if dp[it_N][it_MA-a[it_N]][it_MB-b[it_N]] != math.inf:
                    dp[it_N+1][it_MA][it_MB] = min(dp[it_N][it_MA-a[it_N]][it_MB-b[it_N]] + c[it_N], dp[it_N][it_MA][it_MB])
            else:
                dp[it_N+1][it_MA][it_MB]=dp[it_N][it_MA][it_MB]

    for it_MA in range(MA+1):
        for it_MB in range(MB+1):
#            print(it_N+1,it_MA,it_MB,dp[it_N+1][it_MA][it_MB])

#中身確認
ans = -1
for a in range(1, MA+1):
    for b in range(1, MB+1):
        print(a,b,dp[N][a][b])
        if a/b == rate and dp[N][a][b] != math.inf:
            if ans == -1:
                ans = dp[N][a][b]
            else:
                ans = min([dp[N][a][b], ans])
print(ans)

Submission status: Runtime Error

Solution code:
import math

N, Ma, Mb = map(int,input().split())
rate = Ma / Mb
a = [0] * N
b = [0] * N
c = [0] * N
MA = 0
MB = 0
for i in range(N):
    a[i], b[i], c[i] = map(int, input().split())
    MA += a[i]
    MB += b[i]

dp = [[[math.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 it_N in range(N):
    for it_MA in range(MA+1):
        for it_MB in range(MB+1):
            if it_MA >= a[it_N] and it_MB >= b[it_N]:
                if dp[it_N][it_MA-a[it_N]][it_MB-b[it_N]] != math.inf:
                    dp[it_N+1][it_MA][it_MB] = min(dp[it_N][it_MA-a[it_N]][it_MB-b[it_N]] + c[it_N], dp[it_N][it_MA][it_MB])
            else:
                dp[it_N+1][it_MA][it_MB]=dp[it_N][it_MA][it_MB]

    for it_MA in range(MA+1):
        for it_MB in range(MB+1):
            print(it_N+1,it_MA,it_MB,dp[it_N+1][it_MA][it_MB])

#中身確認
ans = -1
for a in range(1, MA+1):
    for b in range(1, MB+1):
        print(a,b,dp[N][a][b])
        if a/b == rate and dp[N][a][b] != math.inf:
            if ans == -1:
                ans = dp[N][a][b]
            else:
                ans = min([dp[N][a][b], ans])
print(ans)

Submission status: Runtime Error

Solution code:

N, Ma, Mb = map(int,input().split())
rate = Ma / Mb
a = [0] * N
b = [0] * N
c = [0] * N
MA = 0
MB = 0
for i in range(N):
    a[i], b[i], c[i] = map(int, input().split())
    MA += a[i]
    MB += b[i]

dp = [[0 for i in range(MA+1)] for j in range(MB+1)]
src = [[0 for i in range(MA+1)] for j in range(MB+1)]
src[0][0] = 1


for it_N in range(N):
    for it_MA in reversed(range(MA-a[it_N]+1)):
        for it_MB in reversed(range(MB-b[it_N]+1)):
            MAa = it_MA + a[it_N]
            MBb = it_MB + b[it_N]

            if src[it_MA][it_MB] == 1:

                src[MAa][MBb] = 1
                if dp[MAa][MBb] == 0:
                    dp[MAa][MBb] = dp[it_MA][it_MB] + c[it_N]
                else:
                    dp[MAa][MBb] = min([dp[MAa][MBb], dp[it_MA][it_MB] + c[it_N]])


ans = -1
for a in range(1, MA+1):
    for b in range(1, MB+1):
        if a/b == rate and dp[a][b] != 0:
            if ans == -1:
                ans = dp[a][b]
            else:
                ans = min([dp[a][b], ans])
print(ans)

Submission status: Runtime Error

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=abc[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=abc[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: Runtime Error

Solution code:
from itertools import combinations
from bisect import bisect_left
N,Ma,Mb = map(int,input().split())
A = [list(map(int,input().split())) for _ in range(N)]
if N==1:
    if A[0][0]*Mb==A[0][1]*Ma:
        print(A[0][2])
    else:
        print(-1)
else:
    A1 = A[:N//2]  # N//2
    A2 = A[N//2:]  # N-N//2
    B1 = []
    for k in range(1,N//2+1):
        for x in combinations(range(N//2),k):
            cnt1 = 0
            cnt2 = 0
            for i in x:
                cnt1 += Ma*A1[i][1]-Mb*A1[i][0]
                cnt2 += A1[i][2]
            B1.append((cnt1,cnt2))
    B2 = []
    for k in range(1,N-N//2+1):
        for x in combinations(range(N-N//2),k):
            cnt1 = 0
            cnt2 = 0
            for i in x:
                cnt1 += Ma*A2[i][1]-Mb*A2[i][0]
                cnt2 += A2[i][2]
            B2.append((cnt1,cnt2))
    B1 = sorted(B1,key=lambda x:x[1])
    B1 = sorted(B1,key=lambda x:x[0])
    B2 = sorted(B2,key=lambda x:x[1])
    B2 = sorted(B2,key=lambda x:x[0])
    cmin = 10000
    for b1 in B1:
        b,c = b1[0],b1[1]
        ind = bisect_left(B2,(-b,0))
        if B2[ind][0]==-b:
            cmin = min(cmin,c+B2[ind][1])
    if cmin>=10000:
        print(-1)
    else:
        print(cmin)

Submission status: Runtime Error

Solution code:
from itertools import combinations
from bisect import bisect_left
N,Ma,Mb = map(int,input().split())
A = [list(map(int,input().split())) for _ in range(N)]
A1 = A[:N//2]  # N//2
A2 = A[N//2:]  # N-N//2
B1 = []
for k in range(1,N//2+1):
    for x in combinations(range(N//2),k):
        cnt1 = 0
        cnt2 = 0
        for i in x:
            cnt1 += Ma*A1[i][1]-Mb*A1[i][0]
            cnt2 += A1[i][2]
        B1.append((cnt1,cnt2))
B2 = []
for k in range(1,N-N//2+1):
    for x in combinations(range(N-N//2),k):
        cnt1 = 0
        cnt2 = 0
        for i in x:
            cnt1 += Ma*A2[i][1]-Mb*A2[i][0]
            cnt2 += A2[i][2]
        B2.append((cnt1,cnt2))
B1 = sorted(B1,key=lambda x:x[1])
B1 = sorted(B1,key=lambda x:x[0])
B2 = sorted(B2,key=lambda x:x[1])
B2 = sorted(B2,key=lambda x:x[0])
cmin = 10000
for b1 in B1:
    b,c = b1[0],b1[1]
    ind = bisect_left(B2,(-b,0))
    if B2[ind][0]==-b:
        cmin = min(cmin,c+B2[ind][1])
if cmin>=10000:
    print(-1)
else:
    print(cmin)

Submission status: Runtime Error

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):
        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: Runtime Error

Solution code:
from math import gcd
import numpy as np

#       Y = XU
# X^T * Y = X^T * XU
# U = (X^T * X)^(-1) * X^T * Y

epsilon = 0.001

def get_stdin():
    return list(map(int, input().split()))

N, M_a, M_b = get_stdin()
a = []
b = []
c = []

for _ in range(N):
    a_i, b_i, c_i = get_stdin()
    a.append(a_i)
    b.append(b_i)
    c.append(c_i)

# dummy_input_array = [list(map(int, s.split())) for s in dummy_input.split('\n')]
# N = dummy_input_array[0][0]
# M_a = dummy_input_array[0][1]
# M_b = dummy_input_array[0][2]
# Y = np.array([M_a, M_b]).reshape((2, -1))

# a = []
# b = []
# c = []

# for i in range(N):
#     a.append(dummy_input_array[i+1][0])
#     b.append(dummy_input_array[i+1][1])
#     c.append(dummy_input_array[i+1][2])

a = np.array(a)
b = np.array(b)
c = np.array(c)
    
s_idx = [[i for j in range(N) if a[i] % a[j] != 0 and b[i] % b[j] != 0] for i in range(N)]
s_idx = [i for i in range(N) if len(s_idx[i]) > 0]
a_s = a[s_idx]
b_s = b[s_idx]
c_s = c[s_idx]
N_s = len(a_s)
Y_s = Y[s_idx]

Xt = np.array(list(zip(a_s, b_s)))
    
XtX = np.array([
    [
        a_s[i] * a_s[j] + b_s[i] * b_s[j]
             for i in range(N_s)
    ] for j in range(N_s)
])

XtX_det = np.linalg.det(XtX)

if np.abs(XtX_det) < epsilon:
    print(-1)

XtX_inv = np.linalg.inv(XtX)
U = (XtX_inv @ Xt) @ Y_s
U_u = np.mean(U)
ans = U - U_u
err = np.sum(np.abs(ans))

if err > epsilon or np.any(U < 0.0):
    print(-1)

ans_idx = U > epsilon
a_ans = np.sum(a_s.reshape(2, 1)[ans_idx])
b_ans = np.sum(b_s.reshape(2, 1)[ans_idx])


if np.abs(M_a / M_b - a_ans / b_ans) < epsilon:
    sum_c = np.sum(c_s)
    print(sum_c)
else:
    print(-1)

Submission status: Runtime Error

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

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

sumA = sum([ABC[i][0] for i in range(N)])
sumB = sum([ABC[i][1] for i in range(N)])

INF = 10 ** 15
dp = [[INF for j in range(sumA + 1)] for i in range(sumB + 1)]
dp[0][0] = 0

for a, b, c in ABC:
  for i in range(sumA, -1, -1):
    for j in range(sumB, -1, -1):
      if dp[i][j] != INF:
        dp[i + a][j + b] = min(dp[i + a][j + b], dp[i][j] + c)

answer = INF
for i in range(1, sumA + 1):
  for j in range(1, sumB + 1):
    if dp[i][j] != INF and i / j == Ma / Mb:
      answer = min(answer, dp[i][j])
      
print(answer if answer != INF else -1)

Submission status: Runtime Error

Solution code:
#include <algorithm>
#include <bitset>
#include <cassert>
#include <cctype>
#include <cmath>
#include <cstdio>
#include <ctime>
#include <fstream>
#include <functional>
#include <iomanip>
#include <ios>
#include <iostream>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <unordered_map>
#include <vector>

using namespace std;
using ll = long long;

#define REP(i, a) for (int i = 0; i < (a); ++i)
#define FOR(i, a, b) for (int i = (a); i < (b); ++i)
#define FORR(i, a, b) for (int i = (a)-1; i >= (b); --i)
#define ALL(obj) (obj).begin(), (obj).end()
#define SIZE(obj) (int)(obj).sizeT()
#define YESNO(cond, yes, no) \
    { cout << ((cond) ? (yes) : (no)) << endl; }
#define SORT(list) sort(ALL((list)));
#define RSORT(list) sort((list).rbegin(), (list).rend())
#define ASSERT(cond, mes) assert(cond&& mes)

constexpr int MOD = 1'000'000'007;
constexpr int INF = 1'050'000'000;

template <typename T>
T round_up(const T& a, const T& b) {
    return (a + (b - 1)) / b;
}

template <typename T1, typename T2>
istream& operator>>(istream& is, pair<T1, T2>& p) {
    is >> p.first >> p.second;
    return is;
}

template <typename T1, typename T2>
ostream& operator<<(ostream& os, pair<T1, T2>& p) {
    os << p.first << p.second;
    return os;
}

template <typename T>
istream& operator>>(istream& is, vector<T>& v) {
    REP(i, (int)v.size())
    is >> v[i];
    return is;
}

template <typename T>
T clamp(T& n, T a, T b) {
    if (n < a) n = a;
    if (n > b) n = b;
    return n;
}

template <typename T>
static T GCD(T u, T v) {
    T r;
    while (v != 0) {
        r = u % v;
        u = v;
        v = r;
    }
    return u;
}

template <typename T>
static T LCM(T u, T v) {
    return u / GCD(u, v) * v;
}

template <typename T>
std::vector<T> enum_div(T n) {
    std::vector<T> ret;
    for (T i = 1; i * i <= n; ++i) {
        if (n % i == 0) {
            ret.push_back(i);
            if (i * i != n) { ret.push_back(n / i); }
        }
    }
    return ret;
}

template <typename T>
bool chmin(T& a, const T& b) {
    if (a > b) {
        a = b;
        return true;
    }
    return false;
}

template <typename T>
bool chmax(T& a, const T& b) {
    if (a < b) {
        a = b;
        return true;
    }
    return false;
}

struct ToUpper {
    char operator()(char c) {
        return toupper(c);
    }
};

struct ToLower {
    char operator()(char c) {
        return tolower(c);
    }
};

int dp[41][401][401];

int main() {
    cin.tie(0);
    ios::sync_with_stdio(false);
    cout << fixed << setprecision(20);

    int N, Ma, Mb;
    cin >> N >> Ma >> Mb;
    vector<int> A(N), B(N), C(N);
    REP(i, N) {
        cin >> A[i] >> B[i] >> C[i];
    }
    vector<vector<vector<int>>> dp(
        41, vector<vector<int>>(401, vector<int>(401, INF)));
    dp[0][0][0] = 0;
    REP(i, N) {
        REP(j, 401) {
            REP(k, 401) {
                if (dp[i][j][k] == INF) continue;
                chmin(dp[i + 1][j][k], dp[i][j][k]);
                chmin(dp[i + 1][j + A[i]][k + B[i]], dp[i][j][k] + C[i]);
            }
        }
    }

    int ans = INF;
    FOR(i, 1, 401) {
        FOR(j, 1, 401) {
            if (dp[N][i][j] == INF) continue;
            if (Ma * j == Mb * i) { chmin(ans, dp[N][i][j]); }
        }
    }
    if (ans == INF) ans = -1;
    cout << ans << endl;
    return 0;
}

Submission status: Runtime Error

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

items = []
mas = []
mbs = []
costs = []
for i in range(N):
  ma, mb, c = map(int, input().split())
  mas.append(ma)
  mbs.append(mb)
  costs.append(c)

max_cost = 5000
dp = [[[max_cost for k in range(410)] for j in range(410)] for i in range(41)]

for i in range(N):
  for j in range(400):
    for k in range(400):
      if dp[i][j][k] == max_cost:
        continue
      if dp[i][j][k] > dp[i+1][j][k]:
        dp[i][j][k] = dp[i+1][j][k]
      if dp[i+1][j+mas[i]][k+mbs[i]] > dp[i][j][k] + costs[i]:
        dp[i+1][j+mas[i]][k+mbs[i]] = dp[i][j][k] + costs[i]
        
min_cost = 1000000000000000000
for (int wa = 1; wa < 400; ++wa) :
  for (int wb = 1; wb < 400; ++wb) :
    if (wa * mb != wb * ma):
      continue;
      if min_cost > dp[N][wa][wb]:
        min_cost = dp[N][wa][wb]

  
if min_cost == 1000000000000000000:
  print("-1")
else:
  print(min_cost)

Submission status: Runtime Error

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: Runtime Error

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,100000):
			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: Runtime Error

Solution code:
import fractions
 
 
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):
        if not MEMO[i][a][b] is None:
            return MEMO[i][a][b]
 
        if not i < N:
            if 0 < a and 0 < b:
                g = fractions.gcd(a, b)
                if (MA, MB) == (a / g, b / g):
                    return 0
            return float("inf")
 
        res = min(recur(i + 1, a, b) + 0, recur(i + 1, a + A[i], b + B[i]) + C[i])
        MEMO[i][a][b] = res
        return res
 
    x, y, z = 40 + 10, 10 * 10 + 10, 10 * 10 + 10
    MEMO = [[[None] * z for _ in range(y)] for _ in range(x)]
 
    ans = recur(0, 0, 0)
 
    return ans
 
 
if __name__ == '__main__':
    res = solve(*args())
 
    print(-1) if res == float("inf") else print(res)

Submission status: Runtime Error

Solution code:
import fractions


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):
        if not MEMO[i][a][b] is None:
            return MEMO[i][a][b]

        if not i < N:
            if 0 < a and 0 < b:
                g = fractions.gcd(a, b)
                if (MA, MB) == (a / g, b / g):
                    return 0
            return float("inf")

        res = min(recur(i + 1, a, b) + 0, recur(i + 1, a + A[i], b + B[i]) + C[i])
        MEMO[i][a][b] = res
        return res

    x, y, z = 40 + 1, 10 * 10 + 1, 10 * 10 + 1
    MEMO = [[[None] * z for _ in range(y)] for _ in range(x)]

    ans = recur(0, 0, 0)

    return ans


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

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

Submission status: Runtime Error

Solution code:
N,Ma,Mb = map(int,input().split())
dp = [[[10**9 for i in range(400)] for j in range(400)] 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:
                d[i][j][k] = d[i-1][j][k]
            else:
                if k < b:
                    d[i][j][k] = d[i-1][j][k]
                else:
                    d[i][j][k] = min(d[i-1][j][k],d[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(n):
    x = Ma*i
    y = Mb*i
    ans = min(dp[N][x][y])
print(ans)

Submission status: Runtime Error

Solution code:
w=int(input())
n,k=map(int,input().split())

arr=[]
for _ in range(n):
    a,b=map(int,input().split())
    arr.append([a,b])

mat=[[[0]*(w+1) for _ in range(k+1)] for _ in range(n+1)]

#W:全体の幅 N：枚数制約 K：重要度 A:スクショの幅 B：スクショの重要度
#全体の幅と枚数を制約として可能な限り重要度の合計を高くする

for num in range(1,n+1):
    for kn in range(1,k+1):
        for wi in range(1,w+1):
            
            mat[num][kn][wi] = max(mat[num][kn][wi],mat[num-1][kn][wi])
    
            if wi >= arr[num-1][0]:
                mat[num][kn][wi] = max(mat[num-1][kn-1][wi-arr[num-1][0]]+arr[num-1][1],mat[num][kn][wi])

print(mat[-1][-1][-1])

Submission status: Runtime Error

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):
        dp[i+1][j][k]=min(dp[i+1][j][k],dp[i][j][k])
        for k in range(450):
            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: Runtime Error

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

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

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

dp[0][0] = 0

for a, b, cost in items:
    for i in range(B_MAX, -1, -1):
        for j in range(A_MAX, -1, -1):
            if i - b >= 0 and j - a >= 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: Runtime Error

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

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

A_MAX = int(A_MAX)
B_MAX = int(B_MAX)

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(B_MAX + 1):
        for j in range(A_MAX + 1):
            if i - b >= 0 and j - a >= 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: Runtime Error

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

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: Runtime Error

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

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(B_MAX + 1):
        for j in range(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(B_MAX):
    for l in range(A_MAX):
        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: Runtime Error

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

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(B_MAX):
        for j in range(A_MAX):
            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(B_MAX):
    for l in range(A_MAX):
        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: Runtime Error

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(sb + 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: Runtime Error

Solution code:
import numpy

if __name__ == '__main__':
    N,M_a,M_b=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)

    dp=[[[1e10 for i in range(max(B)*(N+1))] for j in range(max(A)*(N+1))] for k in range(N+1)]
    dp[0][0][0]=0

    for i in range(N):
        for c_a in range(max(A)*N):
            for c_b in range(max(B)*N):
                if dp[i][c_a][c_b]==1e10:
                    continue
                dp[i+1][c_a][c_b]=min(dp[i+1][c_a][c_b],dp[i][c_a][c_b])
                dp[i+1][c_a+A[i]][c_b+B[i]]=min(dp[i+1][c_a+A[i]][c_b+B[i]],dp[i][c_a][c_b]+C[i])
    ans_list=[1e10]
    for c_a in A:
        for c_b in B:
            if c_a*M_b==c_b*M_a:
                ans_list.append(dp[N][c_a][c_b])

    ans=min(ans_list)

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

Submission status: Runtime Error

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

m = n * 10 + 1

dp1 = [[float('inf')] * m for i in range(n + 1)]
for i in range(n + 1):
    dp1[i][0] = 0
for i in range(n):
    for j in range(m):
        dp1[i+1][j] = min(dp1[i+1][j], dp1[i][j])
        # i個目を買う
        jj = j + abc[i][0]
        if jj <= 400:
            dp1[i+1][jj] = min(dp1[i+1][jj], dp1[i][j] + abc[i][2])

dp2 = [[float('inf')] * m for i in range(n + 1)]
for i in range(n + 1):
    dp2[i][0] = 0
for i in range(n):
    for j in range(m):
        dp2[i+1][j] = min(dp2[i+1][j], dp2[i][j])
        # i個目を買う
        jj = j + abc[i][1]
        if jj <= 400:
            dp2[i+1][jj] = min(dp2[i+1][jj], dp2[i][j] + abc[i][2])

from fractions import gcd
ans = float('inf')
for i in range(1, m):
    for j in range(1, m):
        d1 = dp1[-1][i]
        d2 = dp2[-1][j]
        g = gcd(i, j)
        if i // g == ma and j // g == mb:
            ans = min(ans, d1 + d2)

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

Submission status: Runtime Error

Solution code:
n, ma, mb = [int(i) for i in input().split()]
lst = [[int(i) for i in input().split()] for _ in range(n)]
lst.sort(key=lambda x: x[2])

def push(k,v):
    if k in dic:
        dic[k] = min(dic[k],v)
    else:
        dic[k] = v


for i in lst:
    k, v = i[0] * mb - i[1] * ma, i[2]
    l = [[j, dic[j]] for j in dic]
    for item in l:
        push(item[0] + k, item[1] + v)
    push(k, v)

print(dic[0] if 0 in dic else '-1')

Submission status: Runtime Error

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())
   
dp = [[float('inf')] * (sum(a)+1) for _ in range(sum(b)+1)]
dp[0][0] = 0
step = [(0, 0)]

for i in range(n):
    ai, bi = a[i], b[i]

    s = step.copy()
    for si in s:
        if dp[si[0]+ai][si[1]+bi] > dp[si[0]][si[1]] + c[i]:
            dp[si[0]+ai][si[1]+bi] = dp[si[0]][si[1]] + c[i]
            step.append((si[0]+ai, si[1]+bi))
    
ans = float('inf')
for i in range(1, min(sum(a)//ma, sum(b)//mb)+1):
    ans = min(ans, dp[ma*i][mb*i])
    
if ans == float('inf'): print(-1)
else : print(ans)

Submission status: Runtime Error

Solution code:
print(oteagedesita)

Submission status: Runtime Error

Solution code:
n,ma,mb=map(int,input().split())
dp=[[10**9 for j in range(400)]for i in range(400)]
dp[0][0]=0 
for i in range(n):
    a,b,c=map(int,input().split())
    for x in range(400):
        for y in range(400):
            if x<a or y<b:
                continue 
            dp[x][y]=min(dp[x][y],dp[x-a][y-b]+c)
mini=10**9 
for i in range(1,41):
    mini=min(mini,dp[ma*i][mb*i])
if mini>=10**9:
    print(-1)
else:
    print(mini)