ABC065D Built[最小生成树]
这题和某道最短路题神似。对于任意点对,将他们连边,不如将他们分别沿$x,y$轴方向上点按顺序连起来,这样不仅可能多连通一些点,也花费更低,所以按照最短路那题的连边方式跑一个kruskal就行了。
1 #include<iostream> 2 #include<cstdio> 3 #include<cstring> 4 #include<algorithm> 5 #include<cmath> 6 #include<queue> 7 #define dbg(x) cerr << #x << " = " << x <<endl 8 using namespace std; 9 typedef long long ll; 10 typedef double db; 11 typedef pair<int,int> pii; 12 template<typename T>inline T _min(T A,T B){return A<B?A:B;} 13 template<typename T>inline T _max(T A,T B){return A>B?A:B;} 14 template<typename T>inline char MIN(T&A,T B){return A>B?(A=B,1):0;} 15 template<typename T>inline char MAX(T&A,T B){return A<B?(A=B,1):0;} 16 template<typename T>inline void _swap(T&A,T&B){A^=B^=A^=B;} 17 template<typename T>inline T read(T&x){ 18 x=0;int f=0;char c;while(!isdigit(c=getchar()))if(c=='-')f=1; 19 while(isdigit(c))x=x*10+(c&15),c=getchar();return f?x=-x:x; 20 } 21 const int N=100000+7; 22 struct thxorz{ 23 int u,v,w; 24 thxorz(int u=0,int v=0,int w=0):u(u),v(v),w(w){} 25 inline bool operator <(const thxorz&A)const{return w<A.w;} 26 }e[N<<1]; 27 int n,tot; 28 struct stothx{int x,y,id;}A[N]; 29 inline bool cmp1(stothx a,stothx b){return a.x<b.x;} 30 inline bool cmp2(stothx a,stothx b){return a.y<b.y;} 31 int anc[N]; 32 ll ans; 33 inline int get_anc(int x){return anc[x]==x?x:anc[x]=get_anc(anc[x]);} 34 35 int main(){//freopen("test.in","r",stdin);//freopen("test.ans","w",stdout); 36 read(n); 37 for(register int i=1;i<=n;++i)read(A[i].x),read(A[i].y),A[i].id=i; 38 sort(A+1,A+n+1,cmp1); 39 for(register int i=1;i<n;++i)e[++tot]=thxorz(A[i].id,A[i+1].id,A[i+1].x-A[i].x); 40 sort(A+1,A+n+1,cmp2); 41 for(register int i=1;i<n;++i)e[++tot]=thxorz(A[i].id,A[i+1].id,A[i+1].y-A[i].y); 42 sort(e+1,e+tot+1); 43 for(register int i=1;i<=n;++i)anc[i]=i; 44 for(register int i=1;i<=tot;++i)if(get_anc(e[i].u)^get_anc(e[i].v))ans+=e[i].w,anc[anc[e[i].u]]=anc[e[i].v]; 45 printf("%lld\n",ans); 46 return 0; 47 }