Problem:
Score : 700 points

Problem Statement

Find the smallest possible sum of the digits in the decimal notation of a positive multiple of K.

Constraints

2 \leq K \leq 10^5

K is an integer.

Input

Input is given from Standard Input in the following format:

K

Output

Print the smallest possible sum of the digits in the decimal notation of a positive multiple of K.

Sample Input 1

6

Sample Output 1

3

12=6×2 yields the smallest sum.

Sample Input 2

41

Sample Output 2

5

11111=41×271 yields the smallest sum.

Sample Input 3

79992

Sample Output 3

36

Solution in Python (3.4.3) (judge verdict: Accepted)

from collections import deque

K = int(input())
adjL = [[] for i in range(K)]
for i in range(K):
    adjL[i].append(((i + 1) % K, 1))  # i→(i+1) に、重み1の辺を張る
    adjL[i].append(((i * 10) % K, 0)) # i→(i*10)に、重み0の辺を張る

# 【01BFS】
cost = [K] * K
cost[1] = 0
Q = deque([(1, 0)]) # 1からスタート
while Q:
    vNow, cNow = Q.popleft()

    if vNow == 0: break # 0に到達したら終了
    if cNow > cost[vNow]: continue

    for v2, wt in adjL[vNow]:
        c2 = cNow + wt
        if c2 < cost[v2]:
            cost[v2] = c2
            if wt == 1:
                # 重み1の辺ならば、キューの末尾に追加する
                Q.append((v2, c2))
            else:
                # 重み0の辺ならば、キューの先頭に追加する
                Q.appendleft((v2, c2))

# 「1→0への最短経路長」+1が求める答え
print(cost[0] + 1)