#include #include #include #include #include using namespace std; struct DSU { vector p, size; explicit DSU(int n) : p(n), size(n, 1) { iota(p.begin(), p.end(), 0); } int find(int x) { return p[x] == x ? x : p[x] = find(p[x]); } bool unite(int a, int b) { a = find(a); b = find(b); if (a == b) return false; if (size[a] < size[b]) swap(a, b); p[b] = a; size[a] += size[b]; return true; } }; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int n; cin >> n; vector x(n), y(n); vector order(n); for (int i = 0; i < n; ++i) cin >> x[i] >> y[i], order[i] = i; vector> edges; auto add_neighbors = [&](const vector &coordinate) { sort(order.begin(), order.end(), [&](int a, int b) { return coordinate[a] < coordinate[b]; }); for (int i = 1; i < n; ++i) { int u = order[i - 1], v = order[i]; edges.push_back({min(abs(x[u] - x[v]), abs(y[u] - y[v])), u, v}); } }; add_neighbors(x); add_neighbors(y); sort(edges.begin(), edges.end()); DSU dsu(n); long long answer = 0; for (auto [w, u, v] : edges) if (dsu.unite(u, v)) answer += w; cout << answer << '\n'; }