idx=*r=1...gets.to_i A=gets.split.map(&:to_i) MEMO={} def getLCM(a,b) MEMO[[a,b].sort]||=A[a].lcm A[b] end puts r.inject([0]){|s,|s+[idx.delete(idx.min_by{|i|[getLCM(s[-1],i),A[i]]})]}.map{|i|A[i]}*" "