Codeforces Raif Round 1 (Div. 1 + Div. 2)
G2
Lucky Numbers (Hard Version)
Codeforces
3000
原题
← G1H →
翻译中…

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

翻译中…

Zookeeper has been teaching his $q$ sheep how to write and how to add. The $i$-th sheep has to write exactly $k$ non-negative integers with the sum $n_i$.

翻译中…

Strangely, sheep have superstitions about digits and believe that the digits $3$, $6$, and $9$ 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 $319$ has fortune $F_{2} + 3F_{0}$.

翻译中…

image

翻译中…

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

翻译中…

Input

翻译中…

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

翻译中…

The next line contains six integers $F_0$, $F_1$, $F_2$, $F_3$, $F_4$, $F_5$ ($1 \leq F_i \leq 10^9$): the fortune assigned to each digit.

翻译中…

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

翻译中…

Each of the next $q$ lines contains a single integer $n_i$ ($1 \leq n_i \leq 999999$): the sum of numbers that $i$-th sheep has to write.

翻译中…

Output

翻译中…

Print $q$ lines, where the $i$-th line contains the maximum sum of fortune of all numbers of the $i$-th sheep.

翻译中…

Note

翻译中…

In the first test case, $57 = 9 + 9 + 39$. The three $9$'s contribute $1 \cdot 3$ and $3$ at the tens position contributes $2 \cdot 1$. Hence the sum of fortune is $11$.

翻译中…

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

翻译中…

样例

Input #1
3
1 2 3 4 5 6
2
57
63
Output #1
11
8
InputCopy OutputCopy
题目信息
题号
1428G2
时间限制
3 s
内存限制
256 MB
标签
动态规划
贪心

题面与样例版权归 Codeforces 及出题人所有;中文翻译由 AI 生成(CI 管线),如有出入请以原文为准。