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