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 C# (Mono 4.6.2.0) (judge verdict: Accepted)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;
using System.Threading.Tasks;

namespace AtCoder
{
    class Node
    {
        public int Distance { get; set; }
        public List<Tuple<Node, int>> Children { get; private set; }
        public Node()
        {
            Distance = int.MaxValue;
            Children = new List<Tuple<Node, int>>();
        }
        public void Add(Node node, int cost)
        {
            Children.Add(new Tuple<Node, int>(node, cost));
        }
    }

    class Program
    {
        private static string Read() { return Console.ReadLine(); }
        private static int ReadInt() { return int.Parse(Read()); }
        private static long ReadLong() { return long.Parse(Read()); }
        private static double ReadDouble() { return double.Parse(Read()); }
        private static int[] ReadInts() { return Array.ConvertAll(Read().Split(), int.Parse); }
        private static long[] ReadLongs() { return Array.ConvertAll(Read().Split(), long.Parse); }
        private static double[] ReadDoubles() { return Array.ConvertAll(Read().Split(), double.Parse); }

        private static int Solve(int K)
        {
            var nodes = new Node[K];
            for (int i = 0; i < K; ++i) { nodes[i] = new Node(); }
            for (int i = 0; i < K; ++i)
            {
                nodes[i].Add(nodes[(i + 1) % K], 1);
                nodes[i].Add(nodes[(i * 10) % K], 0);
            }
            var q = new Queue<Node>();
            nodes[1].Distance = 1;
            q.Enqueue(nodes[1]);
            while (q.Count > 0)
            {
                Node node1 = q.Dequeue();
                foreach (var tuple in node1.Children)
                {
                    Node node2 = tuple.Item1;
                    int cost = tuple.Item2;
                    if (node1.Distance + cost < node2.Distance)
                    {
                        node2.Distance = node1.Distance + cost;
                        q.Enqueue(node2);
                    }
                }
            }
            return nodes[0].Distance;
        }

        static void Main(string[] args)
        {
            int K = ReadInt();
            Console.WriteLine(Solve(K));
        }
    }
}