#include <bits/stdc++.h>

using namespace std;

int main() {

    int n;
    cin >> n;
    
    set<int> col, row;
    bool r_free[n], c_free[n];
    for(int i = 0; i < n; i++) {
        col.insert(i);
        row.insert(i);
        r_free[i] = c_free[i] = true;
    }
    
    int sol = 0;
    for(int i = 0; i < n; i++) {
        int r, c;
        cin >> r >> c;
        r--;
        c--;

        if(r_free[r] && c_free[c]) {
            r_free[r] = c_free[c] = false;
            row.erase(r);
            col.erase(c);
            continue;
        }

        int x = 0, y = 0;
        if(!r_free[r]) {
            auto id = row.lower_bound(r);
            int a = -1, b = -1;
            if(id == row.begin())
                a = *id;
            else if(id == row.end())
                b = *(--id);
            else
                a = *id, b = *(--id);
            if(b == -1) {
                x = a - r;
                r_free[a] = false;
                row.erase(a);
            } else if(a == -1) {
                x = r - b;
                r_free[b] = false;
                row.erase(b);
            } else {
                if(a - r < r - b) {
                    x = a - r;
                    r_free[a] = false;
                    row.erase(a);
                } else {
                    x = r - b;
                    r_free[b] = false;
                    row.erase(b);
                }
            }
        } else {
            r_free[r] = false;
            row.erase(r);
        }
        if(!c_free[c]) {
            auto id = col.lower_bound(c);
            int a = -1, b = -1;
            if(id == col.begin())
                a = *id;
            else if(id == col.end())
                b = *(--id);
            else
                a = *id, b = *(--id);
            if(b == -1) {
                y = a - c;
                c_free[a] = false;
                col.erase(a);
            } else if(a == -1) {
                y = c - b;
                c_free[b] = false;
                col.erase(b);
            } else {
                if(a - c < c - b) {
                    y = a - c;
                    c_free[a] = false;
                    col.erase(a);
                } else {
                    y = c - b;
                    c_free[b] = false;
                    col.erase(b);
                }
            }
        } else {
            c_free[c] = false;
            col.erase(c);
        }
        sol += x + y;
    }
    cout << sol << endl;
    return 0;
}