Hack around the Lock
Time limit5sMemory limit256 MB
Starting from a given K-digit lock setting, find the minimum number of single-wheel rotations needed to visit every other K-digit setting at least once.
- Level
Medium7 of 10
- Topics
- Graph, Math, Greedy, Dynamic programming
- Solved
- No attempts yet
Problem
You have a suitcase with a numeric combination lock made of wheels. Each wheel shows one digit from to , so every setting of the lock is a -digit number (leading zeros are kept and still count as digits). Exactly one setting opens the lock.
You chose the secret setting with a careful random generator, and then you forgot it. Rather than spin the wheels at random, you decide to try every possible setting in turn; because you are unlucky, the correct setting is always the very last one you reach.
In one step you rotate a single wheel by one position, changing that wheel's digit by exactly . A wheel cannot jump directly between and : moving from to (or back) takes steps. After each step you may test the current setting. The initial setting is known to be wrong, so you start from it.
Given the initial setting, determine the minimum number of steps needed so that, starting from it, every other -digit setting is reached (tried) at least once.
Input
The input contains several test instances. Each instance is a single line holding one decimal number , the initial setting. may contain leading zeros, which are part of its digit count (with ); for example, 007 is a -digit setting. The list of instances ends with a line containing -1.
Output
For each instance, print one line containing the minimum number of steps : the fewest single-wheel rotations, starting from the given setting, after which every other -digit setting has been tried at least once.