import std.stdio, std.string, std.conv;
import std.algorithm, std.array, std.range;
import std.typecons;
auto solve(string s_){
    immutable N = s_.chomp.to!int();
    auto x = new int[N];
    auto y = new int[N];
    foreach(i;0..N){
        immutable xy=readln.split.map!(to!int).array();
        x[i]=xy[0];
        y[i]=xy[1];
    }
    alias T = Tuple!(int, "c", int, "a", int, "b");
    T[] es; es.reserve(2*(N-1));
    {
        auto xd = iota(N).array().sort!((a,b)=>x[a]<x[b]);
        auto yd = iota(N).array().sort!((a,b)=>y[a]<y[b]);
        foreach(i;1..N){
            immutable x1=xd[i-1], x2=xd[i];
            es ~= T(x[x2]-x[x1],x1,x2);
            immutable y1=yd[i-1], y2=yd[i];
            es ~= T(y[y2]-y[y1],y1,y2);
        }
    }
    es.sort;
    auto p=iota(N).array();
    auto r=new int[N];
    int find(int x){
        if(x==p[x]) return x;
        return p[x]=find(p[x]);
    }
    void unite(int x, int y){
        x=find(x);
        y=find(y);
        if(x==y) return;
        if(r[x]>r[y]) swap(x,y);
        else if(r[x]==r[y]) ++r[y];
        p[x]=y;
    }
    bool same(int x, int y){
        return find(x)==find(y);
    }
    int c=0;
    foreach(ref e;es) if(!same(e.a,e.b)){
        unite(e.a,e.b);
        c+=e.c;
    }
    return c;
}
void main(){ for(string s; (s=readln.chomp()).length;) writeln(solve(s)); }