n=gets.to_i;
p=*0...n;
f=->a{a==p[a]?a: p[a]=f[p[a]]}
g=$<.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]}}.reduce(:+).sort;
s=0;
g.map{|c,a,b|(s+=c;p[f[a]]=f[b])if f[a]!=f[b]}
p s