class Kumiawase @@checked_list = {} def initialize(start_list) start_list = start_list.dup start_list.delete(nil) sorted_list = start_list.sort @list = start_list.map do |i| sorted_list.index(i) end end def check if @@checked_list.include?(@list) return @@checked_list[@list] end @list.size.times do |s| nokori_list = @list.dup chukan_list = [] i = s nokori_list.delete(i) j = 0 nokori_list.delete(j) chukan_list[j] = i while true j = @list[j] nokori_list.delete(j) if chukan_list.include?(j) if chukan_list[i] == j flag = true else flag = false end break else chukan_list[i] = j end i = @list[i] nokori_list.delete(i) if chukan_list.include?(i) if chukan_list[j] == i flag = true else flag = false end break else chukan_list[j] = i end end if flag if nokori_list.empty? @@checked_list[@list] = true return true else if Kumiawase.new(nokori_list).check @@checked_list[@list] = true return true end end end end @@checked_list[@list] = false return false end end gets a = gets.split.map{|s|s.to_i-1} kumi = Kumiawase.new(a) if kumi.check puts "Yes" else puts "No" end