atcoder#AGC044A. [AGC044A] Pay to Win

[AGC044A] Pay to Win

Score : 400400 points

Problem Statement

You start with the number 00 and you want to reach the number NN.

You can change the number, paying a certain amount of coins, with the following operations:

  • Multiply the number by 22, paying AA coins.
  • Multiply the number by 33, paying BB coins.
  • Multiply the number by 55, paying CC coins.
  • Increase or decrease the number by 11, paying DD coins.

You can perform these operations in arbitrary order and an arbitrary number of times.

What is the minimum number of coins you need to reach NN?

You have to solve T testcases.

Constraints

  • 1T101 \le T \le 10
  • 1N10181 \le N \le 10^{18}
  • 1A,B,C,D1091 \le A, B, C, D \le 10^9
  • All numbers N,A,B,C,DN, A, B, C, D are integers.

Input

The input is given from Standard Input. The first line of the input is

TT

Then, TT lines follow describing the TT testcases. Each of the TT lines has the format

NN AA BB CC DD

Output

For each testcase, print the answer on Standard Output followed by a newline.

5
11 1 2 4 8
11 1 2 2 8
32 10 8 5 4
29384293847243 454353412 332423423 934923490 1
900000000000000000 332423423 454353412 934923490 987654321
20
19
26
3821859835
23441258666

For the first testcase, a sequence of moves that achieves the minimum cost of 2020 is:

  • Initially x=0x = 0.
  • Pay 88 to increase by 11 (x=1x = 1).
  • Pay 11 to multiply by 22 (x=2x = 2).
  • Pay 11 to multiply by 22 (x=4x = 4).
  • Pay 22 to multiply by 33 (x=12x = 12).
  • Pay 88 to decrease by 11 (x=11x = 11).

For the second testcase, a sequence of moves that achieves the minimum cost of 1919 is:

  • Initially x=0x = 0.
  • Pay 88 to increase by 11 (x=1x = 1).
  • Pay 11 to multiply by 22 (x=2x = 2).
  • Pay 22 to multiply by 55 (x=10x = 10).
  • Pay 88 to increase by 11 (x=11x = 11).