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.map.with_index.sort.each_cons(2).map{|(x,i),(y,j)|[y-x,i,j]}};
(a+b).sort_by{|a|a[0]}.map{|c,a,b|(s+=c;p[B]=p[a])if f[a]!=B=f[b]}
p s