def steps(n) i = 0 while n > 0 i += 1 if n%2 == 1 n >>= 1 end i end def mapping(n, p) dis = steps(p) fowdis = p + dis backdis = p - dis map = Array.new(2, -1) map[0] = fowdis if fowdis <= n map[1] = backdis if 1 <= backdis map end def scanroot(map_list, n, goal, fp=Array.new()) puts "0: Start #{n}" if fp.include?(n) or n == -1 fp << -1 puts "1: #{fp}" if false return fp elsif n == goal fp << n puts "2: #{fp}" if false return fp end fp << n 2.times { |i| tfp = scanroot(map_list, map_list[n-1][i], goal, Marshal.load(Marshal.dump(fp))) if tfp[-1] == -1 puts "4: #{fp}" if false next end if tfp[-1] == goal and (fp[-1] != goal or fp.length >= tfp.length) puts "5: #{fp}" if false fp = tfp puts "6: #{fp}" if false end } if fp[-1] != goal fp << -1 puts "7: #{fp}" if false end return fp end n = gets.to_i map_list = Array.new(n) n.times { |i| map_list[i] = mapping(n, i+1) } footprint = Array.new(n, -1) footprint = scanroot(map_list, 1, n) if footprint[-1] == n puts footprint.length-1 else puts -1 end