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