Unit Transformation
Time limit1sMemory limit1024 MB
Find the minimum cost to build a target number from 1 using only operations on the last digit.
- Level
Medium6 of 10
- Topics
- Dynamic programming, BFS, Implementation, Math
- Solved
- No attempts yet
Problem
The kingdom of Numeracija takes great pride in the quality of its numbers, so it collects a tax from its citizens for every change made to a number. Even so, the citizens of Numeracija love transforming numbers.
A group of friends called the Vienetukai ("the Ones") love transforming numbers, always starting from the number . Because they are not wealthy, they use only the cheapest transformations, which act only on the last (least significant) digit:
- add to the last digit of the number — costs gold;
- multiply the last digit of the number by any integer from to — costs gold.
A transformation always acts on the single last digit, and its result takes the place of that digit (so a two-digit product simply lengthens the number). For example, multiplying the last digit of by turns into , and multiplying the last digit of (which is ) by replaces with , giving .
For example, using these operations the number can be obtained from by the following sequence of transformations:
- Multiply by to get .
- Multiply by to get .
- Add to the last digit to get .
- Multiply the last digit by to get .
- Add to the last digit to get .
- Multiply the last digit by to get .
- Multiply the last digit by to get .
This transformation costs gold and can be shown schematically as:
The number could also be obtained more cheaply, for only gold:
Help the Vienetukai save money: find the minimum cost for which they can obtain the given number from using the described transformations.
Input
The first line contains a natural number .
Output
Output a single integer — the minimum cost for which the Vienetukai can obtain the given number from . If cannot be obtained using the described transformations, output .