Kruskal模板

【代码】

Kruskal模板

#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<queue>
#include<set>
using namespace std;
#define f(i,n) for(int i=1;i<=(n);i++)
#define ll long long
#define INF 1<<30
#define N 100010
int read()
{
 	int x=0,f=1;char c=getchar();
 	while(!isdigit(c)){if(c=='-')f=-1;c=getchar();}
 	while( isdigit(c)){x=x*10+c-'0';c=getchar();}
 	return x*f;
}
int n,m; 
struct xj
{
	int x;
	int y;
	int v;
}a[N];
bool cmp(xj a,xj b)
{
	return a.v<b.v;
}
int fa[N];
int find(int x)
{
	if(x==fa[x])return fa[x];
	return fa[x]=find(fa[x]);
}
int main()
{
	n=read();
	m=read();
	f(i,n)fa[i]=i;
	f(i,m)a[i].x=read(),a[i].y=read(),a[i].v=read();
	sort(a+1,a+1+m,cmp);
	int cnt=0;
	f(i,m)
	{
		int u=find(a[i].x),v=find(a[i].y);
		if(u==v)continue;
		fa[u]=v;
		cnt++;
		if(cnt==n-1)break;
	}
}

posted @ 2017-11-09 08:39  qwerfcxs  阅读(153)  评论(0编辑  收藏  举报