import scala.collection.mutable import scala.io.StdIn object Problem003 { case class State(current: Int, steps: Int) object StateOrdering extends Ordering[State] { def compare(a: State, b: State) = a.steps compare b.steps } def bitCount(i: Int): Int = Integer.bitCount(i) def proc(goal: Int): Int = { def inField(i: Int): Boolean = 1 <= i && i <= goal val dp = Array.fill(goal + 1)(Int.MaxValue) val queue = new mutable.PriorityQueue[State]()(StateOrdering.reverse) queue += State(1, 0) while (queue.nonEmpty) { def add(currentPlace: Int, nextSteps: Int): Unit = { if (inField(currentPlace) && dp(currentPlace) > nextSteps) { queue += State(currentPlace, nextSteps) dp(currentPlace) = nextSteps } } val s = queue.dequeue() if (s.current == goal) return s.steps + 1 val back = s.current - bitCount(s.current) val forward = s.current + bitCount(s.current) val nextSteps = s.steps + 1 add(back, nextSteps) add(forward, nextSteps) } -1 } def main(args: Array[String]) { val n = StdIn.readInt() val result = proc(n) println(result) } }