Problem:


Score : 600 points

Problem Statement

The squirrel Chokudai has N acorns.
One day, he decides to do some trades in multiple precious metal exchanges to make more acorns.

His plan is as follows:

Get out of the nest with N acorns in his hands.

Go to Exchange A and do some trades.

Go to Exchange B and do some trades.

Go to Exchange A and do some trades.

Go back to the nest.

In Exchange X (X = A, B), he can perform the following operations any integer number of times (possibly zero) in any order:

Lose g_{X} acorns and gain 1 gram of gold.

Gain g_{X} acorns and lose 1 gram of gold.

Lose s_{X} acorns and gain 1 gram of silver.

Gain s_{X} acorns and lose 1 gram of silver.

Lose b_{X} acorns and gain 1 gram of bronze.

Gain b_{X} acorns and lose 1 gram of bronze.

Naturally, he cannot perform an operation that would leave him with a negative amount of acorns, gold, silver, or bronze.

What is the maximum number of acorns that he can bring to the nest?
Note that gold, silver, or bronze brought to the nest would be worthless because he is just a squirrel.

Constraints

1 \leq N \leq 5000

1 \leq g_{X} \leq 5000

1 \leq s_{X} \leq 5000

1 \leq b_{X} \leq 5000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
g_A s_A b_A
g_B s_B b_B

Output

Print the maximum number of acorns that Chokudai can bring to the nest.

Sample Input 1

23
1 1 1
2 1 1

Sample Output 1

46

He can bring 46 acorns to the nest, as follows:

In Exchange A, trade 23 acorns for 23 grams of gold. {acorns, gold, silver, bronze}={ 0,23,0,0 }

In Exchange B, trade 23 grams of gold for 46 acorns. {acorns, gold, silver, bronze}={ 46,0,0,0 }

In Exchange A, trade nothing. {acorns, gold, silver, bronze}={ 46,0,0,0 }

He cannot have 47 or more acorns, so the answer is 46.



Sample input:
23
1 1 1
2 1 1


Sample output:
46

Submission status: Runtime Error

Solution code:
def napsack(num,getlis):
    DPlis = [0]
    for i in range(N):
        i += 1
        nowgetsum =[DPlis[i-1]]
        for j,k in getlis:
            if i > j:
                nowgetsum.append(DPlis[i-j]+k)
        DPlis.append(max(nowgetsum))
    return DPlis[-1]

N = int(input())
A =[int(i)for i in input().split()]
B =[int(i)for i in input().split()]

ABget =[]
BAget =[]
for i in range(3):
    if A[i] < B[i]:
        ABget.append([A[i],B[i]])
    elif A[i] > B[i]:
        BAget.append([B[i],A[i]])

N2 = N



if len(ABget)==1:
    i,j =ABget[0]
    N2 = N + (N//i)*(j-i)
elif len(ABget)>1:
    N2 = napsack(N,ABget)

    
if len(BAget)==1:
    i,j = BAget[0]
    N2 += (N2//i)*(j-i)
elif len(BAget)>1:
    N3 = napsack(N2,BAget)

print(N3)

Submission status: Runtime Error

Solution code:
N = int(input())
Ga, Sa, Ba = map(int, input().split())
Gb, Sb, Bb = map(int, input().split())
M = max(Ga, Sa, Ba)

dp = [0]*(M+1)
for i in range(M+1, N+M+1):
  dp.append(max(
    dp[-1] + 1,
    dp[-Ga] + Gb,
    dp[-Sa] + Sb,
    dp[-Ba] + Bb,
  ))
N2 = dp[-1]

dp = [0]*(M+1)
for i in range(M+1, N2+M+1):
  dp.append(max(
    dp[-1] + 1,
    dp[-Gb] + Ga,
    dp[-Sb] + Sa,
    dp[-Bb] + Ba,
  ))
print(dp[-1])

Submission status: Runtime Error

Solution code:
# -*- coding: utf-8 -*-
from itertools import product
from heapq import heappop, heappush
import numpy as np


def small_dp(N,k,X):
    if k == 0:
        return N
    if k == 1:
        return X[0][1]*(N//X[0][0]) + N%X[0][0]
    if k == 2:
        return max(X[1][1]*i + X[0][1]*((N-i*X[1][0])//X[0][0]) + (N-i*X[1][0])%X[0][0] for i in range(N//X[1][0]+1))
    if k == 3:
        Y = sorted([(-x[1]/x[0], -x[0], x[1]) for x in X])
        X = [(-y[1], y[2]) for y in Y]
        M = np.arange(N+1)
        dp0 = X[0][1]*(M//X[0][0]) + M%X[0][0]
        d = X[1][1]*(M//X[1][0]) + M%X[1][0]
        dp1f = [np.max(dp0[w::-1] + d[:w+1]) for w in range(N,-1,-1)[:X[0][0]*X[2][0]*X[2][0]]]
        dp1l = [np.max(dp0[w::-1] + d[:w+1]) for w in range(X[0][0]*X[2][0]*X[2][0],-1,-1)]
        f = np.max(dp1f + X[2][1]*(M[:X[0][0]*X[2][0]*X[2][0]]//X[2][0]) + M[:X[0][0]*X[2][0]*X[2][0]]%X[2][0])
        l = np.max(dp1l + X[2][1]*(M[-X[0][0]*X[2][0]*X[2][0]-1:]//X[2][0]) + M[-X[0][0]*X[2][0]*X[2][0]-1:]%X[2][0])
        return max(f,l)

def solve():
    N = int(input())
    A = list(map(int, input().split()))
    B = list(map(int, input().split()))
    
    for C in ((A,B), (B,A)):
        *X, = filter(lambda c: int.__sub__(*c)<0, zip(*C))

        N = small_dp(N, len(X), X)
    res = N

    return str(res)

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

Submission status: Runtime Error

Solution code:
n = int(input())
ga, sa, ba = map(int, input().split())
gb, sb, bb = map(int, input().split())

dp1 = [0] * (n + 1)
if n > 5001:
    for i in range(1, 5001):
        feat = [i]
        if i - ga >= 0:
            feat.append(dp1[i-ga]+gb)
        if i - sa >= 0:
            feat.append(dp1[i-sa]+sb)
        if i - ba >= 0:
            feat.append(dp1[i-ba]+bb)
        dp[i] = max(feat)
    for i in range(5001, n+1):
        dp1[i] = max(i, dp1[i-ga]+gb, dp1[i-sa]+sb, dp1[i-ba]+bb)
else:
    for i in range(1, n+1):
        feat = [i]
        if i - ga >= 0:
            feat.append(dp1[i-ga]+gb)
        if i - sa >= 0:
            feat.append(dp1[i-sa]+sb)
        if i - ba >= 0:
            feat.append(dp1[i-ba]+bb)
        dp1[i] = max(feat)

B = dp1[-1]
dp2 = [0] * (B + 1)
if B > 5001:
    for i in range(1, 5001):
        feat = [i]
        if i - gb >= 0:
            feat.append(dp2[i-gb]+ga)
        if i - sb >= 0:
            feat.append(dp2[i-sb]+sa)
        if i - bb >= 0:
            feat.append(dp2[i-bb]+ba)
        dp2[i] = max(feat)

    for i in range(5001, B+5001):
        dp2[i] = max(i-5000, dp2[i-gb]+ga, dp2[i-sb]+sa, dp2[i-bb]+ba)
else:
    for i in range(1, B+1):
        feat = [i]
        if i - gb >= 0:
            feat.append(dp2[i-gb]+ga)
        if i - sb >= 0:
            feat.append(dp2[i-sb]+sa)
        if i - bb >= 0:
            feat.append(dp2[i-bb]+ba)
        dp2[i] = max(feat)

print(dp2[-1])

Submission status: Runtime Error

Solution code:
n = int(input())
ga, sa, ba = map(int, input().split())
gb, sb, bb = map(int, input().split())

# init N
# A    Donguri
# B    Donguri and metal -> N -> Donguri and metal
# A    Donguri

# first DP
dp = [0] * (n + 1)
for i in range(1, n+1):
    dp[i] = max(i, dp[i-ga] + gb, dp[i-sa] + sb, dp[i-ba] + gb)
print(dp[n])

Submission status: Runtime Error

Solution code:
# -*- coding: utf-8 -*-
from itertools import product
from heapq import heappop, heappush
import numpy as np


def small_dp(N,k,X):
    if k == 0:
        return N
    if k == 1:
        return X[0][1]*(N//X[0][0]) + N%X[0][0]
    if k == 2:
        return np.max((X[0][1]*(np.arange(N+1)//X[0][0]) + np.arange(N+1)%X[0][0])[::-1] + X[1][1]*(np.arange(N+1)//X[i][0]) + np.arange(N+1)%X[1][0])
        for i in range(N//X[0][0]+1):
            j = (N-i*X[0][0])//X[1][0]
            c = max(X[0][1]*i + X[1][1]*j + (N-i*X[0][0])%X[1][0], c)
        return c
    if k == 3:
        dp = np.zeros((k, N+1), dtype=int)
        dp[0] = X[0][1]*(np.arange(N+1)//X[0][0]) + np.arange(N+1)%X[0][0]
        for i in range(1,k):
            d = X[i][1]*(np.arange(N+1)//X[i][0]) + np.arange(N+1)%X[i][0]
            for w in range(1, N+1):
                dp[i,w] = np.max(dp[i-1,w::-1] + d[:w+1])
        N = dp[k-1][N]
        return N

def solve():
    N = int(input())
    A = list(map(int, input().split()))
    B = list(map(int, input().split()))
    
    for C in ((A,B), (B,A)):
        *X, = filter(lambda c: int.__sub__(*c)<0, zip(*C))
        N = small_dp(N, len(X), X)
    res = N

    return str(res)

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

Submission status: Runtime Error

Solution code:
# -*- coding: utf-8 -*-
from itertools import product
from heapq import heappop, heappush
import numpy as np


def small_dp(N,k,X):
    if k == 0:
        return N
    if k == 1:
        return X[0][1]*(N//X[0][0]) + N%X[0][0]
    if k == 10:
        c = 0
        for i in range(N//X[0][0]+1):
            j = (N-i*X[0][0])//X[1][0]
            c = max(X[0][1]*i + X[1][1]*j + (N-i*X[0][0])%X[1][0], c)
        return c
    if k in {2,3}:
        dp = np.zeros((3, N+1), dtype=int)
        dp[0] = X[0][1]*(np.arange(N+1)//X[0][0]) + np.arange(N+1)%X[0][0]
        for i in range(1,3):
            d = X[i][1]*(np.arange(N+1)//X[i][0]) + np.arange(N+1)%X[i][0]
            for w in range(1, N+1):
                dp[i,w] = np.max(dp[i-1,w::-1] + d[:w+1])
        N = dp[2][N]
        return N

def solve():
    N = int(input())
    A = list(map(int, input().split()))
    B = list(map(int, input().split()))
    
    for C in ((A,B), (B,A)):
        *X, = filter(lambda c: int.__sub__(*c)<0, zip(*C))
        N = small_dp(N, len(X), X)
    res = N

    return str(res)

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

Submission status: Runtime Error

Solution code:
# -*- coding: utf-8 -*-
from itertools import product
from heapq import heappop, heappush
import numpy as np


def small_dp(N,k,X):
    if k == 0:
        return N
    if k == 1:
        return X[0][1]*(N//X[0][0]) + N%X[0][0]
    if k == 2:
        c = 0
        for i in range(N//X[0][0]+1):
            j = (N-i*X[0][0])//X[1][0]
            c = max(X[0][1]*i + X[1][1]*j + (N-i*X[0][0])%X[1][0], c)
        return c
    if k == 3:
        dp = np.zeros((3, N+1), dtype=int)
        X[0][1]*np.arange(1,N+1)//X[0][0] + np.arange(1,N+1)%X[0][0]

        dp[0] = X[0][1]*np.repeat(np.arange(N//X[0][0]+1), X[0][0])[:N+1]+np.tile(np.arange(X[0][0]),N//X[0][0]+1)[:N+1]
        for i in range(1,3):
            d = X[i][1]*np.arange(1,N+1)//X[i][0]+np.arange(1,N+1)%X[i][0]
            for w in range(1,N+1):
                dp[i,w] = np.max(dp[i-1,w::-1] + d[:w+1])
        N = dp[3][N]
        return N

def solve():
    N = int(input())
    A = list(map(int, input().split()))
    B = list(map(int, input().split()))
    
    for C in ((A,B), (B,A)):
        *X, = filter(lambda c: int.__sub__(*c)<0, zip(*C))
        N = small_dp(N, len(X), X)
    res = N

    return str(res)

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

Submission status: Runtime Error

Solution code:
N=int(input())

AA = list(map(int,input().split()))
BB = list(map(int,input().split()))

A = AA
B = BB
diff = [B[i]-A[i] for i in range(3)]
mxc = 0
mxarg = -1
for i_g in range( (N+1)//A[0]+1 ):
    if diff[0] < 0 and i_g != 0:
        break
    if A[0]*i_g > N:
        break
    for i_s in range((N+1)//A[1]+1):
        if diff[1] < 0 and i_s != 0:
            break
        if A[0]*i_g+A[1]*i_s > N:
            break
        for i_b in range((N+1)//A[2]+1):
            if diff[2] < 0 and i_b != 0:
                break
            if A[0]*i_g+A[1]*i_s+A[2]*i_b > N:
                break
            cost = diff[0]*i_g + diff[1] *i_s + diff[2]*i_b
            # print((i_g,i_s,i_b),cost)
            if cost > mxc:
                mxc = cost
                mxarg = (i_g,i_s,i_b)
# print(mxarg)
res = N-sum([A[i]*mxarg[i] for i in range(3)])
N = sum([B[i]*mxarg[i] for i in range(3)]) + res
# print(N)

B = AA
A = BB
diff = [B[i]-A[i] for i in range(3)]
mxc = 0
mxarg = -1
for i_g in range( (N+1)//A[0]+1 ):
    if diff[0] < 0 and i_g != 0:
        break
    if A[0]*i_g > N:
        break
    for i_s in range((N+1)//A[1]+1):
        if diff[1] < 0 and i_s != 0:
            break
        if A[0]*i_g+A[1]*i_s > N:
            break
        for i_b in range((N+1)//A[2]+1):
            if diff[2] < 0 and i_b != 0:
                break
            if A[0]*i_g+A[1]*i_s+A[2]*i_b > N:
                break
            cost = diff[0]*i_g + diff[1] *i_s + diff[2]*i_b
            # print((i_g,i_s,i_b),cost)
            if cost > mxc:
                mxc = cost
                mxarg = (i_g,i_s,i_b)
# print(mxarg)
res = N-sum([A[i]*mxarg[i] for i in range(3)])
N = sum([B[i]*mxarg[i] for i in range(3)]) + res
# print(N)
print(N)

Submission status: Runtime Error

Solution code:
# -*- coding: utf-8 -*-
from itertools import product
from heapq import heappop, heappush
import numpy as np


def small_dp(N,k,X):
    if k == 0:
        return N
    if k == 1:
        return X[0][1](N//X[0][0]) + N%X[0][0]
    if k == 2:
        c = 0
        for i in range(N//X[0][0]+1):
            j = (N-i*X[0][0])//X[1][0]
            c = max(X[0][0]*i + X[1][0]*j + (N-i*X[0][0])%X[1][0], c)
        return c
    if k == 3:
        dp = np.zeros((3, N+1), dtype=int)
        dp[0] = np.max((X[0][1]*np.repeat(np.arange(N//X[0][0]+1), X[0][0])[:N+1]+np.tile(np.arange(X[0][0]),N//X[0][0]+1)[:N+1], np.arange(N+1)), axis=0)
        for i,w in product(range(1,3), range(1,N+1)):
            dp[i,w] = np.max((dp[i-1,w::-1] + X[i][1]*np.repeat(np.arange(w//X[i][0]+1), X[i][0])[:w+1]))
        N = dp[-1][N]
        return N

def solve():
    N = int(input())
    A = list(map(int, input().split()))
    B = list(map(int, input().split()))
    
    for C in ((A,B), (B,A)):
        *X, = filter(lambda c: int.__sub__(*c)<0, zip(*C))
        N = small_dp(N, len(X), X)
    res = N

    return str(res)

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

Submission status: Runtime Error

Solution code:
N = int(input())
A =[int(i)for i in input().split()]
B =[int(i)for i in input().split()]

ABget =[]
BAget =[]
for i in range(3):
    if A[i] < B[i]:
        ABget.append([A[i],B[i]])
    elif A[i] > B[i]:
        BAget.append([B[i],A[i]])

N2 = N



if len(ABget)==1:
    i,j =ABget[0]
    N2 = N + (N//i)*(j-i)
elif len(ABget)>1:
    DPlis = [i+1 for i in range(N)]
    DPlis.append(0)
    for n,m in ABget:
        if n <= N:
            DPlis[n-1] = max(DPlis[n-1],m)
    for i in range(N):
        DPlis[i] = max(DPlis[i-1]+1,DPlis[i])
        for n,m in ABget:
            if i+n < N:
                DPlis[i+n] = max(DPlis[i+n],DPlis[i]+m)
    N2 =DPlis[-2]

if len(BAget)==1:
    i,j = BAget[0]
    N2 += (N2//i)*(j-i)
elif len(BAget)>1:
    for n,m in BAget:
        DPlis = [i+1 for i in range(N2)]
        DPlis[n] = m
    DPlis.append(0)
    for n,m in BAget:
        if n <= N2:
            DPlis[n-1] = max(DPlis[n-1],m)
    for i in range(N2):
        DPlis[i] = max(DPlis[i],DPlis[i-1]+1)
        for n,m in BAget:
            if i+n < N2:
                DPlis[i+n] = max(DPlis[i+n],DPlis[i]+m)
    N2 = DPlis[-2]
print(N2)

Submission status: Runtime Error

Solution code:
N = int(input())
A =[int(i)for i in input().split()]
B =[int(i)for i in input().split()]

ABget =[]
BAget =[]
for i in range(3):
    if A[i] < B[i]:
        ABget.append([A[i],B[i]])
    elif A[i] > B[i]:
        BAget.append([B[i],A[i]])

N2 = N



if len(ABget)==1:
    i,j =ABget[0]
    N2 = N + (N//i)*(j-i)
elif len(ABget)>1:
    DPlis = [i+1 for i in range(N)]
    DPlis.append(0)
    for n,m in ABget:
        if n <= N:
            DPlis[n-1] = max(DPlis[n-1],m)
    for i in range(N):
        DPlis[i] = max(DPlis[i-1]+1,DPlis[i])
        for n,m in ABget:
            if i+n < N:
                DPlis[i+n] = max(DPlis[i+n],DPlis[i]+m)
    N2 =DPlis[-2]

if len(BAget)==1:
    i,j = BAget[0]
    N2 += (N2//i)*(j-i)
elif len(BAget)>1:
    for n,m in BAget:
        DPlis[n] = m
    DPlis = [i+1 for i in range(N2)]
    DPlis.append(0)
    for n,m in BAget:
        if n <= N2:
            DPlis[n-1] = max(DPlis[n-1],m)
    for i in range(N2):
        DPlis[i] = max(DPlis[i],DPlis[i-1]+1)
        for n,m in BAget:
            if i+n < N2:
                DPlis[i+n] = max(DPlis[i+n],DPlis[i]+m)
    N2 = DPlis[-2]
print(N2)

Submission status: Runtime Error

Solution code:
//#include <bits/stdc++.h>
#include <iostream>
#include <vector>
#include <list>
#include <map>
#include <unordered_map>
#include <cmath>      // sqrt
#include <cstdlib>    // exit
#include <algorithm>  // min,max
using namespace std;
#define forr(i,m,n) for (int i=(m); i<=(n); i++)
#define forv(i,m,n) for (int i=(m); i>=(n); i--)
#define forall(it,p) for (auto it = p.begin(); it != p.end(); ++it)
#define R 1000000007
#define DBG 0

#define MAXN 5001
typedef long long ll;
//vector< vector<ll> > t;
vector<ll> t[3];

int main() {
  ll n;
  cin >> n;
  vector<int> a(3);
  vector<int> b(3);
  forr(i,0,2)
    cin >> a[i];
  forr(i,0,2)
    cin >> b[i];

  if (DBG) cout << "hi2";

  forr(i,0,2) {
    t[i].resize(n+1);
    t[i][0] = 0;
    forr(j,1,n) t[i][j] = -1;
  }
  if (DBG) cout << "hi";

  ll mx = 0;
  forr(i,0,2) {
    int aa = a[i];
    int x = b[i]-a[i];
    forr(j,1,n) {
      ll tij = -1;
      if (i>0) tij = t[i-1][j];
      if (j >= aa && t[i][j-aa] != -1)
          tij = max(tij, t[i][j-aa]+x);
      t[i][j] = tij;
      mx = max(mx,tij);
    }
  }

  n += mx;

  forr(i,0,2) {
    t[i].resize(n+1);
    t[i][0] = 0;
    forr(j,1,n) t[i][j] = -1;
  }

  mx = 0;
  forr(i,0,2) {
    int bb = b[i];
    int x = a[i]-b[i];
    forr(j,1,n) {
      ll tij = -1;
      if (i>0) tij = t[i-1][j];
      if (j >= bb && t[i][j-bb] != -1)
          tij = max(tij, t[i][j-bb]+x);
      t[i][j] = tij;
      mx = max(mx,tij);
    }
  }

  cout << n+mx << endl;

}

Submission status: Runtime Error

Solution code:
import sys
if sys.version[0] == '2':
    range, input = xrange, raw_input
N = int(input())

A = [int(x) for x in input().split()]
B = [int(x) for x in input().split()]

dp = [N] * (N+1)
for w in range(N+1):
    dp[w] = max(dp[w], max((dp[w-a] + b-a for a, b in zip(A, B) if w-a >= 0), default=0))

M = max(dp)
dp = [M] * (M+1)
for w in range(M+1):
    dp[w] = max(dp[w], max((dp[w-b] + a-b for a, b in zip(A, B) if w-b >= 0), default=0))

print(max(dp))

Submission status: Runtime Error

Solution code:
# -*- coding: utf-8 -*-
from itertools import product
from heapq import heappop, heappush
import numpy as np

def solve():
    N = int(input())
    A = list(map(int, input().split()))
    B = list(map(int, input().split()))
    
    for C in ((A,B), (B,A)):
        X = *filter(lambda c: int.__sub__(*c,)<0, zip(*C,)),
        dp = np.zeros((len(X), N+1), dtype=int)
        if X:
            dp[0] = X[0][1]*np.repeat(np.arange(N//X[0][0]+1), X[0][0])[:N+1]
            for i,w in product(range(1,len(X)), range(1,N+1)):
                dp[i][w] = (dp[i-1, w-X[i][0]*np.arange(w//X[i][0]+1)]+X[i][1]*np.arange(w//X[i][0]+1)).max()
            N = dp[-1][N]
    res = N

    return res

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

Submission status: Runtime Error

Solution code:
def knapsack_123(values,weights,capacity):
    work = [0 for i in range(capacity+1)]
    for v,w in zip(values,weights):
        for c in range(w, capacity+1):
            work[c]=max(work[c],work[c-w]+v)
    return work[-1]
def sol(inp=input):
    n=int(inp())
    prices_a=list(map(int,inp().split()))+[1]
    prices_b=list(map(int,inp().split()))+[1]
    
    valA,_=knapsack_123(values=prices_b,weights=prices_a,capacity=n)
    print(valA)
    valB,_=knapsack_123(values=prices_a,weights=prices_b,capacity=valA)
    return '{}'.format(valB)
print(sol())

Submission status: Runtime Error

Solution code:
###############################################################################

import sys
from sys import stdout
from bisect import bisect_left as binl
from copy import copy, deepcopy
from collections import defaultdict
import math


mod = 1


def intin():
    input_tuple = input().split()
    if len(input_tuple) <= 1:
        return int(input_tuple[0])
    return tuple(map(int, input_tuple))


def intina():
    return [int(i) for i in input().split()]


def intinl(count):
    return [intin() for _ in range(count)]


def modadd(x, y):
    global mod
    return (x + y) % mod


def modmlt(x, y):
    global mod
    return (x * y) % mod


def mod_inv(x):
    # available only when mod is prime
    global mod
    return pow(x, mod - 2, mod)


def gcm(x, y):
    while y != 0:
        z = x % y
        x = y
        y = z
    return x


def combination(x, y):
    assert(x >= y)

    ret = math.factorial(x)
    ret = ret // (math.factorial(x - y) * math.factorial(y))

    return ret


def get_divisors(x):
    retlist = []
    for i in range(1, int(x**0.5) + 3):
        if x % i == 0:
            retlist.append(i)
            retlist.append(x // i)
    return retlist


def get_factors(x):
    retlist = []
    for i in range(2, int(x**0.5) + 3):
        while x % i == 0:
            retlist.append(i)
            x = x // i
    retlist.append(x)
    return retlist


def make_linklist(xylist):
    linklist = {}
    for a, b in xylist:
        linklist.setdefault(a, [])
        linklist.setdefault(b, [])
        linklist[a].append(b)
        linklist[b].append(a)
    return linklist


def calc_longest_distance(linklist, v=1):
    distance_list = {}
    distance_count = 0
    distance = 0
    vlist_previous = []
    vlist = [v]
    nodecount = len(linklist)

    while distance_count < nodecount:
        vlist_next = []
        for v in vlist:
            distance_list[v] = distance
            distance_count += 1
            vlist_next.extend(linklist[v])
        distance += 1
        vlist_to_del = vlist_previous
        vlist_previous = vlist
        vlist = list(set(vlist_next) - set(vlist_to_del))

    max_distance = -1
    max_v = None
    for v, distance in distance_list.items():
        if distance > max_distance:
            max_distance = distance
            max_v = v

    return (max_distance, max_v)


def calc_tree_diameter(linklist, v=1):
    _, u = calc_longest_distance(linklist, v)
    distance, _ = calc_longest_distance(linklist, u)
    return distance


class UnionFind:

    def __init__(self, n):
        self.parent = [i for i in range(n)]

    def root(self, i):
        if self.parent[i] == i:
            return i
        self.parent[i] = self.root(self.parent[i])
        return self.parent[i]

    def unite(self, i, j):
        rooti = self.root(i)
        rootj = self.root(j)
        if rooti == rootj:
            return
        if rooti < rootj:
            self.parent[rootj] = rooti
        else:
            self.parent[rooti] = rootj

    def same(self, i, j):
        return self.root(i) == self.root(j)


###############################################################################


wvalue = []
cache = {}


def f(n, valuesum):
    global cache, wvalue
    if n in cache:
        return cache[n] + valuesum

    rets = {}
    for i, (w, value) in enumerate(wvalue):
        if n >= w:
            rets[i] = f(n - w, valuesum + value)

    if not rets:
        cache[n] = 0
        return valuesum

    maxret = 0
    maxi = -1
    for i, ret in rets.items():
        if ret >= maxret:
            maxi = i
            maxret = ret

    cache[n] = maxret - valuesum
    return maxret


def main():
    global cache, wvalue
    sys.setrecursionlimit(10000)

    n = intin()
    gsb_a = intina()
    gsb_b = intina()

    ga = gsb_a[0]
    sa = gsb_a[1]
    ba = gsb_a[2]

    gb = gsb_b[0]
    sb = gsb_b[1]
    bb = gsb_b[2]

    # a: buy
    if gb - ga > 0:
        wvalue.append((ga, gb - ga))
    if sb - sa > 0:
        wvalue.append((sa, sb - sa))
    if bb - ba > 0:
        wvalue.append((ba, bb - ba))

    value = f(n, 0)
    cache = {}
    wvalue = []

    # b: sell
    n += value

    # b: buy
    if ga - gb > 0:
        wvalue.append((gb, ga - gb))
    if sa - sb > 0:
        wvalue.append((sb, sa - sb))
    if ba - bb > 0:
        wvalue.append((bb, ba - bb))

    value = f(n, 0)
    cache = {}
    wvalue = []

    # a: sell
    n += value

    print(n)


if __name__ == '__main__':
    main()

Submission status: Runtime Error

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


ups = []
downs = []
eqs = []
for i in range(3):
    if A[i] < B[i]:
        ups.append((A[i], B[i]))
    elif A[i] == B[i]:
        eqs.append((A[i], B[i]))
    else:
        downs.append((A[i], B[i]))
ans = N

if len(eqs) == 3:
    print(N)
    exit()

if len(ups) == 0:
    tmp = A
    A = B
    B = tmp
    tmp = ups
    ups = downs
    downs = tmp

if len(ups) == 3:
    gold_diff = B[0]-A[0]
    silver_diff = B[1]-A[1]
    cupper_diff = B[2]-A[2]
    for gold in range(N//A[0]+1):
        left = N - gold*A[0]
        for silver in range(left//A[1]+1):
            cupper = (left - silver*A[1])//A[2]
            tmp_ans = (N
                       + gold*gold_diff
                       + silver*silver_diff
                       + cupper*cupper_diff)
            ans = max(ans, tmp_ans)
    print(ans)
elif len(ups) == 2:
    gold_diff = ups[0][1]-ups[0][0]
    silver_diff = ups[1][1]-ups[1][0]
    for gold in range(N//ups[0][0]+1):
        left = N - gold*ups[0][0]
        silver = left // ups[1][0]
        tmp_ans = (N
                   + gold*gold_diff
                   + silver*silver_diff)
        ans = max(ans, tmp_ans)
    if len(downs) == 1:
        diff = downs[0][0]-downs[0][1]
        ans += (ans // downs[0][1]) * diff
    print(ans)
elif len(ups) == 1:
    bbans = N + (N//ups[0][0])*(ups[0][1]-ups[0][0])
    if len(downs) == 2:
        tmp_ans = bbans
        gold_diff = downs[0][0]-downs[0][1]
        silver_diff = downs[1][0]-downs[1][1]
        for gold in range(bbans//downs[0][1]+1):
            left = bbans - gold*downs[0][1]
            silver = left // downs[1][1]
            tmp_ans = (bbans
                       + gold*gold_diff
                       + silver*silver_diff)
            ans = max(ans, tmp_ans)
    elif len(downs) == 1:
        ans =bbans + (bbans//downs[0][1])*(downs[0][0]-downs[0][1])
    else:
        ans = 
    print(ans)

Submission status: Runtime Error

Solution code:
def getlist():
	return list(map(int, input().split()))

N = int(input())
A = getlist()
B = getlist()


L = [0 for i in range(N + 10)]
l1 = []
l2 = []
for i in range(3):
	if B[i] - A[i] > 0:
		l1.append([A[i], B[i]])
	elif B[i] - A[i] < 0:
		l2.append([B[i], A[i]])

c = 0
n = 0
for i in range(N + 1):
	for j in range(len(l1)):
		x = l1[j][0]
		if i + x <= N:
			if L[i] + l1[j][1] > L[i + x]:
				L[i + x] = L[i] + l1[j][1]
		if L[i] > c:
			c = L[i]
			n = i

N += c - n
if len(l2) == 1:
	N += int(N // l2[0][0]) * l2[0][1] + N % l2[0][0]
	print(N)
elif len(l2) != 2:
	c = 0
	n = 0
	L = [0 for i in range(N + 10)]
	for i in range(N + 1):
		for j in range(len(l2)):
			x = l2[j][0]
			if i + x <= N:
				if L[i] + l2[j][1] > L[i + x]:
					L[i + x] = L[i] + l2[j][1]
			if L[i] > c:
				c = L[i]
				n = i
	N += c - n
	print(N)
else:
	if l2[2][0] < l2[1][0] and l2[2][1] / l2[2][0] > l2[1][1] / l2[1][0]:
		N += int(N // l2[2][0]) * l2[2][1] + (N % l2[2][0])
		print(N)
	elif l2[1][0] < l2[0][0] and l2[1][1] / l2[1][0] > l2[2][1] / l2[2][0]:
		N += int(N // l2[1][0]) * l2[1][1] + (N % l2[1][0])
		print(N)
	else:
		pass

Submission status: Runtime Error

Solution code:
def getlist():
	return list(map(int, input().split()))

N = int(input())
A = getlist()
B = getlist()


L = [0 for i in range(N + 10)]
l1 = []
l2 = []
for i in range(3):
	if B[i] - A[i] > 0:
		l1.append([A[i], B[i]])
	elif B[i] - A[i] < 0:
		l2.append([B[i], A[i]])

c = 0
n = 0
for i in range(N + 1):
	for j in range(len(l1)):
		x = l1[j][0]
		if i + x <= N:
			if L[i] + l1[j][1] > L[i + x]:
				L[i + x] = L[i] + l1[j][1]
		if L[i] > c:
			c = L[i]
			n = i

N += c - n
if len(l2) == 1:
	N += int(N // l2[0][0]) * l2[0][1] + N % l2[0][0]
	print(N)
if len(l2) != 2:
	c = 0
	n = 0
	L = [0 for i in range(N + 10)]
	for i in range(N + 1):
		for j in range(len(l2)):
			x = l2[j][0]
			if i + x <= N:
				if L[i] + l2[j][1] > L[i + x]:
					L[i + x] = L[i] + l2[j][1]
			if L[i] > c:
				c = L[i]
				n = i
	N += c - n
	print(N)
else:
	if l2[2][0] < l2[1][0] and l2[2][1] / l2[2][0] > l2[1][1] / l2[1][0]:
		N += int(N // l2[2][0]) * l2[2][1] + (N % l2[2][0])
		print(N)
	elif l2[1][0] < l2[0][0] and l2[1][1] / l2[1][0] > l2[2][1] / l2[2][0]:
		N += int(N // l2[1][0]) * l2[1][1] + (N % l2[1][0])
		print(N)
	else:
		pass

Submission status: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(10000)

n = int(input())
aa = list(map(int, input().split()))
bb = list(map(int, input().split()))

rates = []
for i in range(3):
	if aa[i] > bb[i]:
		rates.append([bb[i], aa[i]])
	else:
		rates.append([aa[i], bb[i]])

memo = [-1 for _ in range(n + 1)]

#print(rates)

def dp(rest, obtained):
	#print(rest, obtained)
	if rest < 0:
		return -10000

	if memo[rest] != -1:
		return memo[rest]

	ans = max([dp(rest - rates[i][0],  obtained + rates[i][1]) for i in range(3)] + [rest + obtained])
	memo[rest] = ans
	return ans

print(dp(n, 0))
#print(memo)

Submission status: Runtime Error

Solution code:
N = int(input())
ga, sa, ba = map(int, input().split())
gb, sb, bb = map(int, input().split())
dp = [0 for i in range(N+1)]
for i in range(1, N+1):
    koho = max(i, dp[i-1] + 1)
    if i >= ga:
        koho = max(koho, dp[i-ga] + gb)
    if i >= gb:
        koho = max(koho, dp[i-gb] + ga)
    if i >= sa:
        koho = max(koho, dp[i-sa] + sb)
    if i >= sb:
        koho = max(koho, dp[i-sb] + sa)
    if i >= ba:
        koho = max(koho, dp[i-ba] + bb)
    if i >= gb:
        koho = max(koho, dp[i-bb] + ba)
    dp[i] = koho
print(dp[N])

Submission status: Runtime Error

Solution code:
import queue

"""
N = int(input())
#S = input()
# (N,M) = (int(i) for i in input().split(" "))
# A = [int(i) for i in input().split()]
A = []
for i in range(N):
	A.append(int(input()))

print(A)

"""
N = int(input())
A = [int(i) for i in input().split()]
B = [int(i) for i in input().split()]

C = [[B[i]/A[i], A[i], B[i]] for i in range(3)]
C = sorted(C)[::-1]

max_num = N
if C[0][0] > 1:
	max_F = int(N / C[0][1])
	max_num = max_F*C[0][2]
	cur_num = max_num
	lasts = N - max_F * C[0][1]
	if C[1][0] > 1:
		while lasts*C[1][0]+cur_num > max_num and cur_num >= 0:
			max_S = int(lasts / C[1][1])
			max_num_S = max_S*C[1][2]
			cur_num_S = max_num_S
			max_num_T = 0
			lasts_S = lasts - max_S * c[1][1]
			while lasts_S*C[2][0]+cur_num_S > max_num_S and cur_num_S >= 0:
				if cur_num_S + int(lasts_S / C[2][1]) * C[2][2] > max_num_S:
					max_num_S = cur_num_S + int(lasts_S / C[2][1]) * C[2][2]
				lasts_S += c[0][1]
				cur_num_S -= C[1][2]
			if max_num_S + cur_num > max_num:
				max_num = cur_num + max_num_S
			lasts += c[0][1]
			cur_num -= C[0][2]


C = [[A[i]/B[i], B[i], A[i]] for i in range(3)]
C = sorted(C)[::-1]
N = max_num
if C[0][0] > 1:
	max_F = int( N/ C[0][1])
	max_num = max_F*C[0][2]
	cur_num = max_num
	lasts = N - max_F * C[0][1]
	if C[1][0] > 1:
		while lasts*C[1][0]+cur_num > max_num and cur_num >= 0:
			max_S = int(lasts / C[1][1])
			max_num_S = max_S*C[1][2]
			cur_num_S = max_num_S
			max_num_T = 0
			lasts_S = lasts - max_S * c[1][1]
			while lasts_S*C[2][0]+cur_num_S > max_num_S and cur_num_S >= 0:
				if cur_num_S + int(lasts_S / C[2][1]) * C[2][2] > max_num_S:
					max_num_S = cur_num_S + int(lasts_S / C[2][1]) * C[2][2]
				lasts_S += c[0][1]
				cur_num_S -= C[1][2]
			if max_num_S + cur_num > max_num:
				max_num = cur_num + max_num_S
			lasts += c[0][1]
			cur_num -= C[0][2]
print(max_num)