c语言数据结构---kruskal

2023-12-13 08:33:45
#include <cstdio>
#include <string>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int maxn = 1000;
struct node {
		int x,y,z;
}edge[maxn];

	bool cmp(node a,node b) {
		return a.z < b.z;
	}
	
	int fa[maxn];
	
	int n,m;
	
	int u,v,w; 
	
	long long sum;
	
	int get(int x) {//根节点 
		return x == fa[x] ? x : fa[x] = get(fa[x]);
	}
	
	int main(void) {
		scanf("%d%d",&n,&m);
		for(int i = 1; i <= m; i ++) {
			scanf("%d%d%d",&edge[i].x,&edge[i].y,&edge[i].z);
		}
		for(int i = 0; i <= n; i ++) {
			fa[i] = i;
		}
		sort(edge + 1,edge + 1 + m,cmp);
		for(int i = 1; i <= m; i ++) {
			int x = get(edge[i].x);
			int y = get(edge[i].y);
			if(x == y) continue;//成环 
			fa[y] = x;
			sum += edge[i].z;
		}
		int ans = 0;
		for(int i = 1; i <= n; i ++) {
			if(i == fa[i]) ans ++;
		}
		if(ans > 1) puts("impossible");
		else printf("%lld\n",sum);
		return 0;
	} 

文章来源:https://blog.csdn.net/2202_75787160/article/details/134962601
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。