class Calc0101 def initialize(args) args = args.map { |l| l.chomp.split(/\s+/) } @n = args.shift.first.to_i @k = args.shift.first.to_i @xys = args.map { |l| l.map(&:to_i) } end def run pattern = calc_pattern cycles = (1..@n).map { |k| calc_cycle(pattern, k) } cycles.inject { |a, b| a * b / a.gcd(b) } end def calc_cycle(pattern, k) c = 0 s = k begin c += 1 k = pattern[k - 1] end until s == k c end def calc_pattern (1..@n).map { |k| calc_amida(k) } end def calc_amida(k) i = -1 loop do j = @xys.drop(i + 1).index { |x, y| x == k || y == k } break unless j i += j + 1 k = @xys[i][0] == k ? @xys[i][1] : @xys[i][0] end k end end puts Calc0101.new(STDIN.readlines).run if __FILE__ == $0