Transformation from One
Time limit1sMemory limit1024 MB
Starting from 1, you may add 1 to the first or last digit for cost 1, or multiply it by 2..9 for cost 2; find the minimum cost to reach each given number, or -1.
- Level
Hard8 of 10
- Topics
- Backtracking, BFS, Math, Dynamic programming
- Solved
- No attempts yet
Problem
The kingdom of Numeria is very proud of the quality of its numbers, so it charges its citizens a tax for every change made to a number. Even so, the people of Numeria love transforming numbers.
A group of friends, the Units, use the cheapest possible transformations. A number is written in decimal without leading zeros, and only its first (most significant) or last (least significant) digit may be changed:
- Add one to the first or last digit , replacing that digit with the decimal representation of . This costs gold coin. (If , then , so the single digit "9" is replaced by the two digits "10" and the number grows longer.)
- Multiply the first or last digit by any digit from to , replacing it with the decimal representation of . This costs gold coins. (If , that digit is replaced by two digits.)
The Units always start from the number .
For example, can be obtained from with the following sequence, costing gold coins:
- Add to — we get .
- Multiply by — we get .
- Add to the first digit — we get .
- Multiply the first digit by — we get .
- Multiply the first digit by — we get .
- Add to the last digit — we get .
- Multiply the last digit by — we get .
- Multiply the last digit by — we get .
- Add to the last digit — we get .
In the diagram below, the number above each arrow is the cost of that step and the expression below it is the operation applied.
But can also be reached more cheaply, for only gold coins:
Help the Units obtain given numbers using these transformations.
For each of the numbers , find the least cost for which the Units can obtain starting from . If a number cannot be obtained by any sequence of these transformations, its answer is .
Input
The first line contains an integer — the count of numbers in the set. Each of the next lines contains one natural number ().
Output
Print lines. On the -th line print the least cost of the unit transformations that produce from . If no such transformations exist for a given number, print on its line.