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