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 Scala (2.11.7) (judge verdict: Wrong Answer)

import java.io._
import java.util.StringTokenizer
import scala.util.control.Breaks.{breakable,break}
import scala.collection.mutable.PriorityQueue

object Main extends App {
  val in = new InputReader(System.in)
  val pw = new PrintWriter(System.out)

  val K = in.next().toInt


  // Dijkstra
  val edge = Array.fill[List[(Int, Int)]](K+1)(Nil)  // (node, cost)
  for(i <- 0 until K) {
    edge(i) = ((i*10) % K, 0) :: edge(i)
    edge(i) = (i+1, 1) :: edge(i)
  }

  // fro から to への最短距離(v は頂点数)
  def dijkstra(from: Int, to: Int, v: Int): Int = {
    val MAX = Int.MaxValue

    val dist = Array.fill(v)(MAX)   // fro からの距離を格納する
    val check = new Array[Boolean](v)  // すでにその頂点からを調べたかのフラグ

    dist(from) = 0

    val pq = new PriorityQueue[(Int, Int)]  // (-cost, node) queue
    pq.enqueue((-0, from))

    // 頂点は v 個あるので、v 周する
    for(i <- 0 until v) {
      // 調べ済みでない頂点のうち、最も近い頂点を now に入れる
      var nowNode = -1       // このターンにフォーカスするノード

      breakable {
        nowNode = pq.dequeue._2  // 最小コストから貪欲に取っていく
        if(!check(nowNode)){  // まだチェックされていないノードだったら決定
          check(nowNode) = true
          break
        }
      }

      // その頂点からたどり着ける頂点の情報を更新する
      for((nextNode, cost) <- edge(nowNode)) {
        val nextDist = dist(nowNode) + cost
        if(nextDist < dist(nextNode)){  // 既存の通路より近いなら更新
          dist(nextNode) = nextDist
          pq.enqueue((-nextDist, nextNode))
        }
      }
    }

    return dist(to)
  }


  println(dijkstra(0, K, K+1))
}


class InputReader(stream: InputStream) {
  private val reader = new BufferedReader(new InputStreamReader(stream))
  private var tokenizer: StringTokenizer = new StringTokenizer(reader.readLine())
  def next(): String = {
    while (!tokenizer.hasMoreTokens()) {
      tokenizer = new StringTokenizer(reader.readLine())
    }
    tokenizer.nextToken()
  }
}