class Calc0003 def initialize(args) args = args.map { |l| l.chomp.split(/\s+/) } @n = args.shift.first.to_i @visited = Array.new(@n) { false } end def run queue = [[1, 1]] until queue.empty? k, c = queue.shift return c if k == @n queue.push(*cands(k).map { |m| [m, c + 1] }) end -1 end def cands(k) d = k.to_s(2).count('1') r = [k - d, k + d].select { |m| 1 <= m && m <= @n && !@visited[m] } r.each do |m| @visited[m] = true end r end end puts Calc0003.new(STDIN.readlines).run if __FILE__ == $0