BZOJ P1083 繁忙的都市【Kruskal】

最小生成树模板题,没什么好说的。

#include <cmath>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#define DB double
#define SG string
#define LL long long
#define Fp(A,B,C,D) for(A=B;A<=C;A+=D)
#define Fm(A,B,C,D) for(A=B;A>=C;A-=D)
#define Clear(A) memset(A,0,sizeof(A))
#define Copy(A,B) memcpy(A,B,sizeof(A))
using namespace std;
const LL Max=1e5+5;
const LL Mod=1e9+7;
const LL Inf=1e18;
struct Node{
	LL X,Y,Z;
}G[Max];
LL N,M,Cnt,Ans,F[Max];
inline LL Read(){
	LL X=0;char CH=getchar();bool F=0;
	while(CH>'9'||CH<'0'){if(CH=='-')F=1;CH=getchar();}
	while(CH>='0'&&CH<='9'){X=(X<<1)+(X<<3)+CH-'0';CH=getchar();}
	return F?-X:X;
}
inline void Write(LL X){
	if(X<0)X=-X,putchar('-');
	if(X>9)Write(X/10);
	putchar(X%10+48);
}
LL Find(LL X){
	return X==F[X]?X:F[X]=Find(F[X]);
}
bool Cmp(Node A,Node B){
	return A.Z<B.Z;
}
int main(){
	LL I,J,K;
	N=Read(),M=Read();
	Fp(I,1,M,1){
		G[I].X=Read(),G[I].Y=Read(),G[I].Z=Read();
	}sort(G+1,G+1+M,Cmp);
	Fp(I,1,N,1){
		F[I]=I;
	}
	Fp(I,1,M,1){
		LL Fx=Find(G[I].X);
		LL Fy=Find(G[I].Y);
		if(Fx!=Fy){
			Ans=G[I].Z;
			F[Fx]=Fy;
			if(++Cnt==N-1){
				break;
			}
		}
	}Write(N-1);putchar(' ');Write(Ans);
	return 0;
}


猜你喜欢

转载自blog.csdn.net/yanzhenhuai/article/details/80458510