import qualified Data.ByteString.Char8 as C
import qualified Data.IntSet as S
import Data.Ord
import Prelude hiding (head, tail, null, filter)
import Data.Vector.Unboxed

main = C.interact $ put . sol . get

get = unfoldr (C.readInt . C.dropWhile (<'0'))

put = C.pack . show

sol :: Vector Int -> Int
sol v = prim es
  where
  n = head v
  u = tail v
  vs = generate n (\i -> (u!(2*i),u!(2*i+1)))
  es = fromList [(cost i j,i,j) | i <- [0..n-2], j <- [i+1..n-1]] :: Vector (Int, Int, Int)
  cost i j = min (abs (fst (vs!i) - fst (vs!j))) (abs (snd (vs!i) - snd (vs!j)))

-- Prim's minimum spanning tree 
prim es = f (S.singleton i0) 0
  where
  (_,i0,_) = head es
  f s a = if null r then a else f (S.insert i (S.insert j s)) (c+a)
    where
    r = filter (\(_,i,j) -> S.member i s /= S.member j s) es
    (c,i,j) = minimumBy (comparing cost) r

cost :: (Int, Int, Int) -> Int
cost (c,_,_) = c