#include <cstdio>
#include <iostream>
#include <queue>
#include <algorithm>
using namespace std;
typedef long long ll;
const ll inf = 0x3f3f3f3f;
const ll N = 1e5 + 9;
struct edge {
int x, y, w;
}e[N << 2], a[N << 2];
struct node {
int x, y, id;
}p[N];
bool cmp1(node a, node b) {return a.x < b.x;}
bool cmp2(node a, node b) {return a.y < b.y;}
bool cmp3(edge a, edge b) {return a.w < b.w;}
int f[N << 2];
int Find(int x){return f[x] == x?x:f[x] = Find(f[x]);}
signed main() {
int n;scanf("%d", &n);
for (int i = 1; i <= n; i ++) {
scanf("%d%d", &p[i].x, &p[i].y);
p[i].id = i;
}
for (int i = 0; i <= n + 2; i ++) f[i] = i;
sort(p + 1, p + 1 + n, cmp1);
int nn = 0;
for (int i = 1; i < n; i ++) e[++nn] = {p[i].id, p[i + 1].id, abs(p[i].x - p[i + 1].x)};
sort(p + 1, p + 1 + n, cmp2);
for (int i = 1; i < n; i++) e[++nn] = {p[i].id, p[i + 1].id, abs(p[i].y - p[i + 1].y)};
sort(e + 1, e + 1 + nn, cmp3);
int ans =0 ;
for (int i = 1; i <= nn; i ++) {
int fx = Find(e[i].x);
int fy = Find(e[i].y);
if (fx == fy)continue;
f[fx] = fy;
ans += e[i].w;
}
printf("%d\n", ans);
}
原文:https://www.cnblogs.com/Xiao-yan/p/14688979.html