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

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

def solve():
    N = int(input())
    A = list(map(int, input().split()))
    B = list(map(int, input().split()))

    dp = [[0 for _ in range(N+1)] for _ in range(4)]
    X, Y = [N]+A, [N]+B
    for i,w in product(range(4), range(1,N+1)):
        dp[i][w] = max(dp[i-1][w-X[i]*j]+Y[i]*j for j in range(0,w//X[i]+1) if w>=X[i]*j) if w>=X[i] else dp[i-1][w]
    N = dp[3][N]
    #print(dp)
    dp = [[0 for _ in range(N+1)] for _ in range(4)]
    X, Y = [N]+B, [N]+A
    for i,w in product(range(4), range(1,N+1)):
        dp[i][w] = max(dp[i-1][w-X[i]*j]+Y[i]*j for j in range(0,w//X[i]+1) if w>=X[i]*j) if w>=X[i] else dp[i-1][w]
    res = dp[3][N]
    #print(dp)
    return res

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

Submission status: Wrong Answer

Solution code:
N = int(input())
A_lis = list(map(int, input().split()))
B_lis = list(map(int, input().split()))

f = [(B_lis[_]/A_lis[_], A_lis[_], B_lis[_]) for _ in range(3)]

f.sort()
f.reverse()

rest = N
gain = 0

for j in range(3):
  if f[j][0] > 1.0:
    g = rest // f[j][1]
    rest -= g * f[j][1]
    gain += g * f[j][2]

print(gain+rest)

Submission status: Wrong Answer

Solution code:
n = int(input())
ra = [int(v) for v in input().split()]
rb = [int(v) for v in input().split()]
p = [n, 0, 0, 0]

rab = []
rba = []
for i in range(3):
  rab.append((i, rb[i] / ra[i]))
  rba.append((i, ra[i] / rb[i]))

rab.sort(key=lambda x:x[1], reverse=True)
rba.sort(key=lambda x:x[1], reverse=True)

#print("巣", p)

#Aで金銀銅に交換
for r in rab:
  i = r[0]
  d = p[0]
  p[0] = d % ra[i]
  p[i + 1] = d // ra[i]

#print("Aで金銀銅に交換", p)
#print("rate", rab)

#Bでドングリに交換
for i in range(3):
  p[0] += p[i + 1] * rb[i]
  p[i + 1] = 0
#print("Bでドングリに交換", p)
#print("rate", rb)

#Bで金銀銅に交換
for r in rba:
  i = r[0]
  d = p[0]
  p[0] = d % rb[i]
  p[i + 1] = d // rb[i]

#print("Bで金銀銅に交換", p)

#Aでドングリに交換
for i in range(3):
  p[0] += p[i + 1] * ra[i]
  p[i + 1] = 0
#print("Aでドングリに交換", p)
print(p[0])

Submission status: Wrong Answer

Solution code:
import fractions
from functools import reduce

N = int(input())

A = list(map(int,input().split()))
B = list(map(int,input().split()))

#座圧用
def lcm_base(x, y):
    return (x * y) // fractions.gcd(x, y)

def lcm_list(numbers):
    return reduce(lcm_base, numbers, 1)


#0gold，1silver，2blonze
R = [A[0]/B[0],A[1]/B[1],A[2]/B[2]]
AtoB,BtoA = [],[]
for i in range(len(R)):
    if R[i]>1: BtoA.append(i)
    elif R[i]<1: AtoB.append(i)
        
#AtoB Phase
if len(AtoB)==1:
    N = ((N//A[AtoB[0]])*B[AtoB[0]])+(N%A[AtoB[0]])
elif len(AtoB)>=2: #ここでdp
    max_rate = 0
    best = 0
    for v in AtoB:
        r = B[v]/A[v]
        if r>max_rate:
            best = v
            max_rate = r
    LCM = lcm_list([A[v] for v in AtoB])
    Nstock = (N//LCM)*(LCM//A[best])*B[best]#事前計算しておくN
    N = N%LCM
    
    dp = [N for i in range(N+1)]
    for i in range(1,N+1):
        O = [dp[i-1]]
        for j in range(len(AtoB)):
            if i>=A[AtoB[j]]: O.append(dp[i-A[AtoB[j]]]-A[AtoB[j]]+B[AtoB[j]])
        dp[i] = max(O)
    N = dp[N]+Nstock
    
#BtoA Phase
if len(BtoA)==1:
    N = ((N//B[BtoA[0]])*A[BtoA[0]])+(N%B[BtoA[0]])
elif len(BtoA)>=2: #ここでdp
    max_rate = 0
    best = 0
    for v in BtoA:
        r = A[v]/B[v]
        if r>max_rate:
            best = v
            max_rate = r
    LCM = lcm_list([B[v] for v in BtoA])
    Nstock = (N//LCM)*(LCM//B[best])*A[best]#事前計算しておくN
    N = N%LCM
    
    dp = [N for i in range(N+1)]
    for i in range(1,N+1):
        O = [dp[i-1]]
        for j in range(len(BtoA)):
            if i>=B[BtoA[j]]: O.append(dp[i-B[BtoA[j]]]-B[BtoA[j]]+A[BtoA[j]])
        dp[i] = max(O)
    N = dp[N]+Nstock
    
print(N)

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10 ** 5)


def LI(): return [int(x) for x in sys.stdin.readline().split()]


def main():
    N = int(input())
    A = LI()
    B = LI()
    if A == B:
        print(N)
        return
    BA = [(B[i]/A[i], i) for i in range(3)]
    AB = [(A[i]/B[i], i) for i in range(3)]
    BA.sort(reverse=True)
    AB.sort(reverse=True)
    now = N

    money = [0, 0, 0]
    for (_, i) in filter(lambda a: a[0] > 1, BA):
        money[i] = now//A[i]
        now = now % A[i]
    for i in range(3):
        now += money[i]*B[i]

    money = [0, 0, 0]
    for (_, i) in filter(lambda a: a[0] > 1, AB):
        money[i] = now//B[i]
        now = now % B[i]
    for i in range(3):
        now += money[i]*A[i]
    print(now)


main()

Submission status: Wrong Answer

Solution code:
N = int(input())
A_lis = list(map(int, input().split()))
B_lis = list(map(int, input().split()))

f = [(B_lis[_]/A_lis[_], A_lis[_], B_lis[_]) for _ in range(3)]

f.sort()
f.reverse()

rest = N
gain = 0

for j in range(3):
  if f[j][0] > 1.0:
    g = rest // f[j][1]
    rest -= g * f[j][1]
    gain += g * f[j][2]

print(rest, gain)
print(gain+rest)

Submission status: Wrong Answer

Solution code:
n=int(input())
ga,sa,ba=map(int,input().split())
gb,sb,bb=map(int,input().split())
rate=[[gb/ga,gb,ga],[sb/sa,sb,sa],[bb/ba,bb,ba]]
rate=sorted(rate,key=lambda x:x[2])
rate=sorted(rate,reverse=True,key=lambda x:x[0])
ret=0
for i in range(3):
  if rate[0][0]>1:
    ret+=rate[0][1]*(n//rate[0][2])
    n-=n//rate[0][2]
  if rate[1][0]>1:
    ret+=rate[1][1]*(n//rate[1][2])
    n-=n//rate[1][2]
  if rate[2][0]>1:
    ret+=rate[2][1]*(n//rate[2][2])
    n-=n//rate[2][2]
n+=ret
rate=[[ga/gb,ga,gb],[sa/sb,sa,sb],[ba/bb,ba,bb]]
rate=sorted(rate,key=lambda x:x[2])
rate=sorted(rate,reverse=True,key=lambda x:x[0])
ret=0
for i in range(3):
  if rate[0][0]>1:
    ret+=rate[0][1]*(n//rate[0][2])
    n-=n//rate[0][2]
  if rate[1][0]>1:
    ret+=rate[1][1]*(n//rate[1][2])
    n-=n//rate[1][2]
  if rate[2][0]>1:
    ret+=rate[2][1]*(n//rate[2][2])
    n-=n//rate[2][2]
n+=ret
print(n)

Submission status: Wrong Answer

Solution code:
# coding:utf-8

import math

def main():
    n = int(raw_input())
    ga, sa, ba = map(int, raw_input().split())
    gb, sb, bb = map(int, raw_input().split())

    a = [[ga,gb],[sa,sb],[ba,bb]]
    mx = 0
    for i in a:
        for j in a:
            if i == j:
                continue
            for k in a:
                if k == i or k == j:
                    continue
                tmpN = n
                c1 = 0
                c2 = 0
                c3 = 0
                if float(i[1]) / i[0] >= 1:
                    c1 = tmpN / i[0]
                    tmpN = tmpN % i[0]
                if float(j[1]) / j[0] >= 1:
                    c2 = tmpN / j[0]
                    tmpN = tmpN % j[0]
                if float(k[1]) / k[0] >= 1:
                    c3 = tmpN / k[0]
                    tmpN = tmpN % k[0]
                tmpT = tmpN + c1 * i[1] + c2 * j[1] + c3 * k[1]
                mx = max(mx,tmpT)
    n = mx
    mx = 0
    for i in a:
        for j in a:
            if i == j:
                continue
            for k in a:
                if k == i or k == j:
                    continue
                tmpN = n
                c1 = 0
                c2 = 0
                c3 = 0
                if float(i[0]) / i[1] >= 1:
                    c1 = tmpN / i[1]
                    tmpN = tmpN % i[1]
                if float(j[0]) / j[1] >= 1:
                    c2 = tmpN / j[1]
                    tmpN = tmpN % j[1]
                if float(k[0]) / k[1] >= 1:
                    c3 = tmpN / k[1]
                    tmpN = tmpN % k[1]
                tmpT = tmpN + c1 * i[0] + c2 * j[0] + c3 * k[0]
                mx = max(mx,tmpT)
    print mx

if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
n=int(input())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
ea=[]
eb=[]
for i in range(3):
    if(a[i]<b[i]):
        ea.append((a[i],b[i]))
    elif(a[i]>b[i]):
        eb.append((b[i],a[i]))
ea.sort(reverse=True)
eb.sort(reverse=True)
def main(ea,n):
    if(len(ea)==1):
        fa=n%ea[0][0]+n//ea[0][0]*ea[0][1]
    elif(len(ea)==2):
        ga,gb=ea[0]
        ba,bb=ea[1]
        fa=n
        for i in range(n+1):
            if(ga*i>n):
                break
            k=n-ga*i
            tmp=i*(gb-ga)+k%ba+(k//ba)*bb
            fa=max(tmp,fa)
    elif(len(ea)==3):
        ga,gb=ea[0]
        sa,sb=ea[1]
        ba,bb=ea[2]
        fa=n
        if(ga==sa):
            return main([ea[0],ea[2]],n)
        if(sa==ba):
            return main([ea[0],ea[1]],n)
        for i in range(n+1):
            if(ga*i>n):
                break
            for j in range(n+1):
                if(ga*i+sa*i>n):
                    break
                k=n-ga*i-sa*j
                tmp=i*(gb-ga)+j*(sb-sa)+k%ba+k//ba*bb
                fa=max(tmp,fa)
    else:
        fa=n
    return fa
n=main(ea,n)
n=main(eb,n)
print(n)

Submission status: Wrong Answer

Solution code:
# coding:utf-8

import math

def main():
    n = int(raw_input())
    ga, sa, ba = map(int, raw_input().split())
    gb, sb, bb = map(int, raw_input().split())

    a = [[ga,gb],[sa,sb],[ba,bb]]
    mx = 0
    for i in a:
        for j in a:
            if i == j:
                continue
            for k in a:
                if k == i or k == j:
                    continue
                tmpN = n
                c1 = 0
                c2 = 0
                c3 = 0
                if float(i[1]) / i[0] >= 1:
                    c1 = tmpN / i[0]
                    tmpN = tmpN % i[0]
                if float(j[1]) / j[0] >= 1:
                    c2 = tmpN / j[0]
                    tmpN = tmpN % j[0]
                if float(k[1]) / k[0] >= 1:
                    c3 = tmpN / k[0]
                    tmpN = tmpN % k[0]
                tmpT = tmpN + c1 * i[1] + c2 * j[1] + c3 * k[1]
                mx = max(mx,tmpT)
    n = mx
    for i in a:
        for j in a:
            if i == j:
                continue
            for k in a:
                if k == i or k == j:
                    continue
                tmpN = n
                c1 = 0
                c2 = 0
                c3 = 0
                if float(i[0]) / i[1] >= 1:
                    c1 = tmpN / i[1]
                    tmpN = tmpN % i[1]
                if float(j[0]) / j[1] >= 1:
                    c2 = tmpN / j[1]
                    tmpN = tmpN % j[1]
                if float(k[0]) / k[1] >= 1:
                    c3 = tmpN / k[1]
                    tmpN = tmpN % k[1]
                tmpT = tmpN + c1 * i[0] + c2 * j[0] + c3 * k[0]
                mx = max(mx,tmpT)
    print mx

if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10 ** 5)


def LI(): return [int(x) for x in sys.stdin.readline().split()]


def main():
    N = int(input())
    A = LI()
    B = LI()
    if A == B:
        print(N)
        return
    BA = [((B[i]-A[i])/A[i], i) for i in range(3)]
    AB = [((A[i]-B[i])/B[i], i) for i in range(3)]
    BA.sort(reverse=True)
    AB.sort(reverse=True)
    now = N

    money = [0, 0, 0]
    for (d, i) in filter(lambda a: a[0] > 0, BA):
        if now < A[i]:
            continue
        money[i] = now//A[i]
        now = now % A[i]
    for i in range(3):
        now += money[i]*B[i]

    money = [0, 0, 0]
    for (d, i) in filter(lambda a: a[0] > 0, AB):
        if now < B[i]:
            continue
        money[i] = now//B[i]
        now = now % B[i]
    for i in range(3):
        now += money[i]*A[i]
    print(now)


main()

Submission status: Wrong Answer

Solution code:
# coding:utf-8

import math

def main():
    n = int(raw_input())
    ga, sa, ba = map(int, raw_input().split())
    gb, sb, bb = map(int, raw_input().split())

    a = [[ga,gb],[sa,sb],[ba,bb]]
    mx = 0
    for i in a:
        for j in a:
            if i == j:
                continue
            for k in a:
                if k == i or k == j:
                    continue
                tmpN = n
                c1 = 0
                c2 = 0
                c3 = 0
                if float(i[1]) / i[0] > 1:
                    c1 = tmpN / i[0]
                    tmpN = tmpN % i[0]
                if float(j[1]) / j[0] > 1:
                    c2 = tmpN / j[0]
                    tmpN = tmpN % j[0]
                if float(k[1]) / k[0] > 1:
                    c3 = tmpN / k[0]
                    tmpN = tmpN % k[0]
                tmpT = tmpN + c1 * i[1] + c2 * j[1] + c3 * k[1]
                mx = max(mx,tmpT)
    n = mx
    for i in a:
        for j in a:
            if i == j:
                continue
            for k in a:
                if k == i or k == j:
                    continue
                tmpN = n
                c1 = 0
                c2 = 0
                c3 = 0
                if float(i[0]) / i[1] > 1:
                    c1 = tmpN / i[1]
                    tmpN = tmpN % i[1]
                if float(j[0]) / j[1] > 1:
                    c2 = tmpN / j[1]
                    tmpN = tmpN % j[1]
                if float(k[0]) / k[1] > 1:
                    c3 = tmpN / k[1]
                    tmpN = tmpN % k[1]
                tmpT = tmpN + c1 * i[0] + c2 * j[0] + c3 * k[0]
                mx = max(mx,tmpT)
    print mx

if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
def gcd(a,b):
    if b>a:
        a,b=b,a
    while b:
        a,b=b, a%b
    return a

def f(a,b,N):
    l=[]
    for i in range(3):
        if a[i]<b[i]: l.append(i)

    if len(l)==0: return N
    if len(l)==1:
        l=l[0]
        return (N//a[l])*b[l]+N%a[l]
    elif len(l)==2:
        x,y=l[0],l[1]
        lcm=a[x]*a[y]//gcd(a[x],a[y])

        n1,n2=N-N%lcm,N%lcm
        ans1=max(n1*b[x]//a[x],n1*b[y]//a[y])
        i=0
        ans2=0
        while i*a[x]<=n2:
            j=(n2-i*a[x])//a[y]
            ans2=max(ans2, i*b[x]+j*b[y]+ (n2-i*a[x]-j*a[y]) )
            i+=1
        return ans1+ans2
        
    else:
        lcm=a[0]*a[1]//gcd(a[0],a[1])
        lcm=lcm*a[2]//gcd(a[2],lcm)
        n1,n2=N-N%lcm,N%lcm
        ans1=max(n1*b[i]//a[i] for i in range(3))
        i=0
        ans2=0
        while i*a[0]<=n2:
            j=0
            while  j*a[1]<=n2-i*a[0]:
                k=(n2-i*a[0]-j*a[1])//a[2]
                ans2=max(ans2, i*b[0]+j*b[1]+k*b[2] + (n2-i*a[0]-j*a[1]-k*a[2]) )
                j+=1
            i+=1
        return ans1+ans2

import sys
N=int(input())

A=list(map(int,input().split()))
B=list(map(int,input().split()))

N=f(A,B,N)
N=f(B,A,N)
print(int(N))

Submission status: Wrong Answer

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(5001)]
memo[0] = 0

def dp(rest):
	if rest < 0:
		return -10000
	if memo[rest] != -1:
		return memo[rest]
	
	ans = max(dp(rest - rates[0][0]) + rates[0][1], dp(rest - rates[0][0]) + rates[0][1], dp(rest - rates[0][0]) + rates[0][1], memo[rest] + rest)
	memo[rest] = ans
	return ans

print(dp(n))

Submission status: Wrong Answer

Solution code:
n=int(input())
ga,sa,ba=map(int,input().split())
gb,sb,bb=map(int,input().split())
g=-ga+gb,-sa+sb,-ba+bb
dp=[-10000 for i in range(5000)]+[0 for i in range(n+1)]
for i in range(5000,n+5001):
  dp[i]=max(dp[i-ga]+g[0],dp[i-sa]+g[1],dp[i-ba]+g[2],0)
d=dp[n+5000]+n
dp2=[-10000 for i in range(5000)]+[0 for i in range(d+1)]
for i in range(5000,n+5001):
  dp2[i]=max(dp2[i-gb]-g[0],dp2[i-sb]-g[1],dp2[i-bb]-g[2],0)
print(dp2[d+5000]+d)

Submission status: Wrong Answer

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


x = N
y = N
for j in range(3):
    k = 0
    ref = 0
    for i in range(3):
        if ref < x//A[i]*(B[i]-A[i]):
            k = i
            ref = x//A[i]*(B[i]-A[i])
    y += ref
    x -= x//A[k]

x = y
for j in range(3):
    k = 0
    ref = 0
    for i in range(3):
        if ref < x//B[i]*(A[i]-B[i]):
            k = i
            ref = x//B[i]*(A[i]-B[i])
    y += ref
    x -= x//B[k]

print(y)

Submission status: Wrong Answer

Solution code:
n = int(input())
x0, y0, z0 = map(int, input().split())
x1, y1, z1 = map(int, input().split())

x, y, z = (min(x0, x1), min(y0, y1), min(z0, z1))
dx, dy, dz = (abs(x0-x1), abs(y0-y1), abs(z1-z0))

sa = 0
for i in range(5010):
    for j in range(5010):
        if x * i + y * j <= n:
            k = (n - (x*i+y*j))//z
            sa = max(sa, i*dx+j*dy+k*dz)
        else:
            break
print(n + sa)

Submission status: Wrong Answer

Solution code:
inpl = lambda: list(map(int,input().split()))
N = int(input())
rate1 = []
rate1.append(inpl())
rate1.append(inpl())
rate = []
for i in range(3):
    rate.append([rate1[0][i],rate1[1][i]])
    rate[-1].sort()
    rate[-1][1] = rate[-1][1] - rate[-1][0]

ans = 0
dp = [0]
q = [0]*3
for i in range(1,N+1):
    for k in range(3):
        if i >= rate[k][0]:
            q[k] = dp[i-rate[k][0]] + rate[k][1]
        else:
            q[k] = 0
    dp.append(max(dp[i-1], max(q)))
print(dp[N]+N)

Submission status: Wrong Answer

Solution code:
import itertools

n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))

a = [1]+a
b = [1]+b


ans = n

l = [0,1,2,3]

for v in itertools.permutations(l,4):
    p = [n, 0, 0, 0]
    q = [0, 0, 0, 0]
    for x in v:
        q[x] += p[0]//a[x]
        p[0] = p[0]%a[x]
    p=[p[i]+q[i] for i in range(4)]

    q = [0,0,0,0]
    for i in range(4):
        q[0] += p[i] * b[i]
    r=[q[0],0,0,0]

    for w in itertools.permutations(l,4):
        p = [i for i in r]
        q = [0, 0, 0, 0]
        for y in w:
            q[y] += p[0] // b[y]
            p[0] = p[0] % b[y]
        p = [p[i] + q[i] for i in range(4)]

        q = [0,0,0,0]
        for i in range(4):
            q[0] += p[i] * a[i]
        ans = max(ans, q[0])

print(ans)

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10 ** 5)


def LI(): return [int(x) for x in sys.stdin.readline().split()]


def main():
    N = int(input())
    A = LI()
    B = LI()
    if A == B:
        print(N)
        return
    BA = [((B[i]-A[i])/A[i], i) for i in range(3)]
    AB = [((A[i]-B[i])/B[i], i) for i in range(3)]
    BA.sort(reverse=True)
    AB.sort(reverse=True)
    now = N

    money = [0, 0, 0]
    for (d, i) in BA:
        if d <= 0:
            break
        if now < A[i]:
            continue
        money[i] = now//A[i]
        now = now % A[i]
    for i in range(3):
        now += money[i]*B[i]

    money = [0, 0, 0]
    for (d, i) in AB:
        if d <= 0:
            break
        if now < B[i]:
            continue
        money[i] = now//B[i]
        now = now % B[i]
    for i in range(3):
        now += money[i]*A[i]
    print(now)


main()

Submission status: Wrong Answer

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

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)


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


def main():
    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]

    g = s = b = 0

    # a: buy
    g_ratio = gb / ga
    s_ratio = sb / sa
    b_ratio = bb / ba
    ratios = [(g_ratio, 'g'), (s_ratio, 's'), (b_ratio, 'b')]
    ratios.sort(reverse=True)

    for ratio, t in ratios:
        if t == 'g':
            if ga >= gb:
                continue
            nn = n
            n -= ga * (nn // ga)
            g += nn // ga
        if t == 's':
            if sa >= sb:
                continue
            nn = n
            n -= sa * (nn // sa)
            s += nn // sa
        if t == 'b':
            if ba >= bb:
                continue
            nn = n
            n -= ba * (nn // ba)
            b += nn // ba

    # b: sell
    n += g * gb
    n += s * sb
    n += b * bb
    g = s = b = 0

    # b: buy
    g_ratio = ga / gb
    s_ratio = sa / sb
    b_ratio = ba / bb
    ratios = [(g_ratio, 'g'), (s_ratio, 's'), (b_ratio, 'b')]
    ratios.sort(reverse=True)

    for ratio, t in ratios:
        if t == 'g':
            if gb >= ga:
                continue
            nn = n
            n -= gb * (nn // gb)
            g += nn // gb
        if t == 's':
            if sb >= sa:
                continue
            nn = n
            n -= sb * (nn // sb)
            s += nn // sb
        if t == 'b':
            if bb >= ba:
                continue
            nn = n
            n -= bb * (nn // bb)
            b += nn // bb

    # a: sell
    n += g * ga
    n += s * sa
    n += b * ba
    g = s = b = 0

    print(n)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
#!venv/bin/python
 
import math
import numpy as np
import random
import copy
import statistics 
import bisect
import heapq
from collections import defaultdict 
import time
import sys
from pprint import pprint
import itertools

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

dealdA = []
for order in itertools.permutations(range(4)):
    status = [0,0,0,N]
    for type in order:
        if type == 3:
            break
        status[type] += status[3] // A[type]
        status[3] = status[3] % A[type]
    dealdA.append(status)
dealdB = []
for f_status in dealdA:
    for type in range(3):
        f_status[3] += B[type] * f_status[type]
        f_status[type] = 0
    for order in itertools.permutations(range(4)):
        status = f_status.copy()
        for type in order:
            if type == 3:
                break
            status[type] += status[3] // B[type]
            status[3] = status[3] % B[type]
        dealdB.append(status)

count = []
for f_status in dealdB:
    status = f_status.copy()
    for type in range(3):
        status[3] += A[type] * status[type]
        status[type] = 0
    count.append(status[3])

print(max(count))

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python
from __future__ import division, print_function

import os
import sys
from io import BytesIO, IOBase

if sys.version_info[0] < 3:
    from __builtin__ import xrange as range
    from future_builtins import ascii, filter, hex, map, oct, zip


def main():
    n = int(input())
    a = list(map(int, input().split()))
    b = list(map(int, input().split()))

    s = 0

    a.append(1)
    b.append(1)

    c = sorted(zip(a, b), key=lambda x: -max(x) / min(x))

    for ai, bi in c:
        mi = min(ai, bi)
        ma = max(ai, bi)

        s += ma * (n // mi)
        n %= mi

    print(s)



# region fastio

BUFSIZE = 8192


class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)


class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")


def print(*args, **kwargs):
    """Prints the values to a stream, or to sys.stdout by default."""
    sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
    at_start = True
    for x in args:
        if not at_start:
            file.write(sep)
        file.write(str(x))
        at_start = False
    file.write(kwargs.pop("end", "\n"))
    if kwargs.pop("flush", False):
        file.flush()


if sys.version_info[0] < 3:
    sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
    sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)

input = lambda: sys.stdin.readline().rstrip("\r\n")

# endregion

if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
N = int(input())

ga, sa, ba = list(map(int, input().split()))
a = {'g': ga, 's': sa, 'b': ba}
gb, sb, bb = list(map(int, input().split()))
b = {'g': gb, 's': sb, 'b': bb}


rate = [['g', ga/gb], ['s', sa/sb], ['b', ba/bb]]
rate.sort(key=lambda x: x[1])

A = {'g': 0, 's': 0, 'b': 0, 'd': N}
for r in rate:
    if r[1] < 1:
        A[r[0]] = A['d']//a[r[0]]
        A['d'] -= A[r[0]]

B = {'g': 0, 's': 0, 'b': 0, 'd': A['d']+A['g']*b['g']+A['s']*b['s']+A['b']*b['b']}
rate.sort(reverse=True ,key=lambda x: x[1])
for r in rate:
    if r[1] > 1:
        A[r[0]] = A['d']//a[r[0]]
        A['d'] -= A[r[0]]

print(B['d']+B['g']*a['g']+B['s']*a['s']+B['b']*a['b'])

Submission status: Wrong Answer

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

def solve():
    N = int(input())
    A = [0]+list(map(int, input().split()))
    B = [0]+list(map(int, input().split()))

    dp = [[0,0,0,0] for _ in range(N+max(A+B)+5)]
    X, Y = A, B
    for i,w in product(range(1,4), range(1,N+1)):
        dp[w][i] = max(dp[w-X[i]*j][i-1]+Y[i]*j for j in range(0,w//X[i]+1) if w>=X[i]*j) if w>=X[i] else dp[w][i-1]
    N = dp[N][3]
    dp = [[0,0,0,0] for _ in range(N+1)]
    X, Y = B, A
    for i,w in product(range(1,4), range(1,N+1)):
        dp[w][i] = max(dp[w-X[i]*j][i-1]+Y[i]*j for j in range(0,w//X[i]+1) if w>=X[i]*j) if w>=X[i] else dp[w][i-1]
    res = dp[N][3]
    return res

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