#P1428G2. Lucky Numbers (Hard Version)
Lucky Numbers (Hard Version)
Description
This is the hard version of the problem. The only difference is in the constraint on . You can make hacks only if all versions of the problem are solved.
Zookeeper has been teaching his sheep how to write and how to add. The -th sheep has to write exactly non-negative integers with the sum .
Strangely, sheep have superstitions about digits and believe that the digits , , and 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 has fortune .

Each sheep wants to maximize the sum of fortune among all its written integers. Can you help them?
The first line contains a single integer (): the number of numbers each sheep has to write.
The next line contains six integers , , , , , (): the fortune assigned to each digit.
The next line contains a single integer (): the number of sheep.
Each of the next lines contains a single integer (): the sum of numbers that -th sheep has to write.
Print lines, where the -th line contains the maximum sum of fortune of all numbers of the -th sheep.
Input
The first line contains a single integer (): the number of numbers each sheep has to write.
The next line contains six integers , , , , , (): the fortune assigned to each digit.
The next line contains a single integer (): the number of sheep.
Each of the next lines contains a single integer (): the sum of numbers that -th sheep has to write.
Output
Print lines, where the -th line contains the maximum sum of fortune of all numbers of the -th sheep.
Note
In the first test case, . The three 's contribute and at the tens position contributes . Hence the sum of fortune is .
In the second test case, . The sum of fortune is .