20pts求助
查看原帖
20pts求助
865812
_Paimon_楼主2025/1/20 16:00
#include <bits/stdc++.h>
using namespace std;
#define ll long long
struct edge{int u,v,w;};
struct node{int x,y,z,d;};
ll n,m=0,f[10000005];
edge e[10000005];
node a[10000005];
void init(){for(int i=1;i<=n;i++)f[i]=i;}
bool cmpa(node x,node y){return x.x<y.x;}
bool cmpb(node x,node y){return x.y<y.y;}
bool cmpc(node x,node y){return x.z<y.z;}
bool cmpd(edge x,edge y){return x.w<y.w;}
int find(int x){if(x==f[x])return x;return f[x]=find(f[x]);}
void merge(int x,int y){int fx=find(x),fy=find(y);if(fx!=fy) f[fx]=fy;}
int dis(int x,int y){return min(abs(a[x].x-a[y].x),min(abs(a[x].y-a[y].y),abs(a[x].z-a[y].z)));}
ll ans=0;
void kruskal(){
	init();
	int cnt=0;
	for(int i=1;i<=m;i++){
		int v=e[i].v;
		int u=e[i].u;
		ll w=e[i].w;
		if(find(v)!=find(u)){
			ans+=w;
			merge(u,v);
			cnt++;
			if(cnt==n-1)return;
		}
	}	
}
int main(){
	cin>>n;
	for(int i=1;i<=n;i++){cin>>a[i].x>>a[i].y>>a[i].z;a[i].d=i;}
	sort(a+1,a+n+1,cmpa);
	for(int i=1;i<n;i++)e[++m]=edge{a[i].d,a[i+1].d,dis(i,i+1)};
	sort(a+1,a+n+1,cmpb);
	for(int i=1;i<n;i++)e[++m]=edge{a[i].d,a[i+1].d,dis(i,i+1)};
	sort(a+1,a+n+1,cmpc);
	for(int i=1;i<n;i++)e[++m]=edge{a[i].d,a[i+1].d,dis(i,i+1)};
	sort(e+1,e+n+1,cmpd);
	kruskal();
	cout<<ans;
	return 0;
} 

2025/1/20 16:00
加载中...