n = gets.to_i gets.to_i.times{ a,b = gets.split.map(&:to_i) if n == a n = b elsif n == b n = a end } p n