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,b|a,b=f[a],f[b];(s+=c;p[b]=a)if a!=b};
p s