Given a set of allowed digits, find the fewest factors (minus one) whose digits all come from the set and whose product is K.
Medium6Dynamic programmingNumber theoryNo attempts yetTime limit1sMemory limit128 MBThere is a game where you combine number cards, arithmetic operator cards, and bracket cards to build a target value. Jin likes this game and packed the cards for the IT engineering college retreat, but did not bring the whole set. Of the operator cards Jin brought only multiplication cards, and of the number cards only N of the digit types from 0 through 9. So Jin changed the rules to a multiplication game.
In the multiplication game you build a fixed number out of number cards and multiplication cards. The team that uses the fewest multiplication cards wins. Jin has plenty of every digit type that was packed, so no type ever runs short and the same type can be used again as many times as needed.
Number cards placed side by side form a multi-digit number. Every digit in the decimal writing of that number must belong to the packed digit types, and a writing with a leading zero is not used. So building K means writing K as a product of numbers whose every digit belongs to the packed types. A product of t numbers uses t−1 multiplication cards.
For example, if the packed digit types are 2, 3, 6, then 64 can be built as 32×2, which uses one multiplication card. No method uses fewer.
Given the packed digit types and a target number, find the minimum number of multiplication cards.
The first line contains the number of test cases T (1≤T≤50).
The first line of each test case contains the number of digit types N (1≤N≤10) and the N digit types, separated by spaces. The types are distinct and each lies between 0 and 9.
The second line of each test case contains the number of queries M (1≤M≤20).
Each of the next M lines contains one target natural number K (1≤K≤106).
For each query print the minimum number of multiplication cards on its own line. If K cannot be built, print -1.