h={} n,*a=$<.read.split.map &:to_i (1..n).map{|i|e=a[i-1];a[i,n]=a[i,n].sort{|x,y|l=h[[e,x].sort]||=e.lcm x m=h[[e,y].sort]||=e.lcm y z=l<=>m z==0?x<=>y:z}} $><