atcoder#DIVERTA20192D. Squirrel Merchant

Squirrel Merchant

Score : 600600 points

Problem Statement

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

His plan is as follows:

  1. Get out of the nest with NN acorns in his hands.
  2. Go to Exchange AA and do some trades.
  3. Go to Exchange BB and do some trades.
  4. Go to Exchange AA and do some trades.
  5. Go back to the nest.

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

  • Lose gXg_{X} acorns and gain 11 gram of gold.
  • Gain gXg_{X} acorns and lose 11 gram of gold.
  • Lose sXs_{X} acorns and gain 11 gram of silver.
  • Gain sXs_{X} acorns and lose 11 gram of silver.
  • Lose bXb_{X} acorns and gain 11 gram of bronze.
  • Gain bXb_{X} acorns and lose 11 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

  • 1N50001 \leq N \leq 5000
  • 1gX50001 \leq g_{X} \leq 5000
  • 1sX50001 \leq s_{X} \leq 5000
  • 1bX50001 \leq b_{X} \leq 5000
  • All values in input are integers.

Input

Input is given from Standard Input in the following format:

NN

gAg_A sAs_A bAb_A

gBg_B sBs_B bBb_B

Output

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

23
1 1 1
2 1 1
46

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

  • In Exchange AA, trade 2323 acorns for 2323 grams of gold. {acorns, gold, silver, bronze}={ 0,23,0,00,23,0,0 }
  • In Exchange BB, trade 2323 grams of gold for 4646 acorns. {acorns, gold, silver, bronze}={ 46,0,0,046,0,0,0 }
  • In Exchange AA, trade nothing. {acorns, gold, silver, bronze}={ 46,0,0,046,0,0,0 }

He cannot have 4747 or more acorns, so the answer is 4646.