暑期留校——AcWing--kruskal算法模板

#include
#include
#include
#include

using namespace std;

int n ,m;
int INF = 0x3f3f3f3f;
int p[10000010];

struct edge{
	int a, b, w;
	bool operator < (const edge &W)const
	{
		return w < W.w;
	}
}edges[10000010];

int find(int x)
{
	if(p[x] != x)  p[x] = find(p[x]);
	return p[x];
}
int kruskal()
{
	for(int i = 1;i <= n;i ++ ) p[i] = i;
	
	int cnt = 0, ans = 0;
	for(int i = 0;i < m;i ++)
	{
		int a = edges[i].a, b = edges[i].b, w = edges[i].w;
		a = find(a), b = find(b);
		if(find(a) != find(b))
		{
			p[a] = b;
			cnt ++;
			ans = ans + w;
		}
	}
	if(cnt < n - 1) return INF;
	return ans;
}
int main()
{
	scanf("%d%d",&n, &m);
	for(int i = 0;i < m;i ++ )
	{
		int a , b , w;
		scanf("%d%d%d",&a,&b,&w);
		edges[i] = {a, b, w};
	}
	
	sort(edges,edges + m);
	int res = kruskal();
	
	if(res == INF) printf("impossible\n");
	else printf("%d",res);
	
	return 0;
}

你可能感兴趣的:(算法,算法,图论,蓝桥杯)