This page is still under construction.

Parts of this page are still being built. What you see may change.

Hack around the Lock

Time limit5sMemory limit256 MB

Summary
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 KK wheels. Each wheel shows one digit from 00 to 99, so every setting of the lock is a KK-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 11. A wheel cannot jump directly between 00 and 99: moving from 00 to 99 (or back) takes 99 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 KK-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 NN, the initial setting. NN may contain leading zeros, which are part of its digit count KK (with 1≤K≤71 \le K \le 7); for example, 007 is a 33-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 SS: the fewest single-wheel rotations, starting from the given setting, after which every other KK-digit setting has been tried at least once.

Examples4

  1. Example 1

    Input
    5
    00
    -1
    
    Expected output
    13
    99
    
  2. Example 2

    Input
    0
    9
    -1
    
    Expected output
    9
    9
    
  3. Example 3

    Input
    007
    -1
    
    Expected output
    999
    
  4. Example 4

    Input
    55
    10
    99
    42
    -1
    
    Expected output
    99
    99
    99
    99