#P1428G2. Lucky Numbers (Hard Version)

Lucky Numbers (Hard Version)

No submission language available for this problem.

Description

This is the hard version of the problem. The only difference is in the constraint on qq. You can make hacks only if all versions of the problem are solved.

Zookeeper has been teaching his qq sheep how to write and how to add. The ii-th sheep has to write exactly kk non-negative integers with the sum nin_i.

Strangely, sheep have superstitions about digits and believe that the digits 33, 66, and 99 are lucky. To them, the fortune of a number depends on the decimal representation of the number; the fortune of a number is equal to the sum of fortunes of its digits, and the fortune of a digit depends on its value and position and can be described by the following table. For example, the number 319319 has fortune F2+3F0F_{2} + 3F_{0}.

Each sheep wants to maximize the sum of fortune among all its kk written integers. Can you help them?

The first line contains a single integer kk (1k9999991 \leq k \leq 999999): the number of numbers each sheep has to write.

The next line contains six integers F0F_0, F1F_1, F2F_2, F3F_3, F4F_4, F5F_5 (1Fi1091 \leq F_i \leq 10^9): the fortune assigned to each digit.

The next line contains a single integer qq (1q1000001 \leq q \leq 100\,000): the number of sheep.

Each of the next qq lines contains a single integer nin_i (1ni9999991 \leq n_i \leq 999999): the sum of numbers that ii-th sheep has to write.

Print qq lines, where the ii-th line contains the maximum sum of fortune of all numbers of the ii-th sheep.

Input

The first line contains a single integer kk (1k9999991 \leq k \leq 999999): the number of numbers each sheep has to write.

The next line contains six integers F0F_0, F1F_1, F2F_2, F3F_3, F4F_4, F5F_5 (1Fi1091 \leq F_i \leq 10^9): the fortune assigned to each digit.

The next line contains a single integer qq (1q1000001 \leq q \leq 100\,000): the number of sheep.

Each of the next qq lines contains a single integer nin_i (1ni9999991 \leq n_i \leq 999999): the sum of numbers that ii-th sheep has to write.

Output

Print qq lines, where the ii-th line contains the maximum sum of fortune of all numbers of the ii-th sheep.

Samples

Sample Input 1

3
1 2 3 4 5 6
2
57
63

Sample Output 1

11
8

Note

In the first test case, 57=9+9+3957 = 9 + 9 + 39. The three 99's contribute 131 \cdot 3 and 33 at the tens position contributes 212 \cdot 1. Hence the sum of fortune is 1111.

In the second test case, 63=35+19+963 = 35 + 19 + 9. The sum of fortune is 88.