p=*0..gets.to_i;s=0;f=->a{a>p[a]?p[a]=f[p[a]]:a};a,b=$<.map(&:split).transpose.map{|a|i=0;a.map{|a|[a.to_i,i+=1]}.sort.each_cons(2).map{|(x,i),(y,j)|[y-x,i,j]}};(a+b).sort_by{|a|a[0]}.map{|c,*a|a,b=a.map(f).sort;a<b&&(s+=c;p[b]=a)};p s