题目大意:
二维平面上给n个点,定义两点的距离为: m i n ( ∣ x i − x j ∣ , ∣ y i − y j ∣ ) min(|x_i-x_j|,|y_i-y_j|) min(∣xi−xj∣,∣yi−yj∣).问你最小生成树大小
题目思路:
假设只有一维,那么直接 m a x − m i n max-min max−min即可.这里两个维度叠加之后,分别对 x , y x,y x,y排序,相邻点之间存边.最后对边排序后跑一遍kruskal即可。
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define pii pair<int,int>
#define pb push_back
#define mp make_pair
#define fi first
#define se second
const int maxn = 1e5 + 5;
const int mod = 1e9 + 7;
struct Node
{
int x , y , id;
}a[maxn];
bool cmp1 (const Node & a , const Node & b){
return a.x < b.x;
}
bool cmp2 (const Node & a , const Node & b){
return a.y < b.y;
}
int f[maxn];
int getf (int x) {return x == f[x] ? x : f[x] = getf(f[x]);}
bool mer (int a , int b)
{
int fa = getf(a) , fb = getf(b);
if (fa == fb) return false;
f[fb] = fa;
return true;
}
struct Edge
{
int u , v , w;
bool operator < (const Edge & a)
{
return w < a.w;
}
}e[maxn * 2];
int main()
{
ios::sync_with_stdio(false);
int n; cin >> n;
for (int i = 1 ; i <= n ; i++){
cin >> a[i].x >> a[i].y;
a[i].id = i;
f[i] = i;
}
int cnt = 0;
sort(a + 1 , a + 1 + n , cmp1);
for (int i = 1 ; i < n ; i++){
e[++cnt].u = a[i].id;
e[cnt].v = a[i + 1].id;
e[cnt].w = a[i + 1].x - a[i].x;
}
sort(a + 1 , a + 1 + n , cmp2);
for (int i = 1 ; i < n ; i++){
e[++cnt].u = a[i].id;
e[cnt].v = a[i + 1].id;
e[cnt].w = a[i + 1].y - a[i].y;
}
sort(e + 1 , e + 1 + cnt);
ll ans = 0;
for (int i = 1 ; i <= cnt ; i++){
if (mer(e[i].u , e[i].v)) ans += e[i].w;
}
cout << ans << endl;
return 0;
}