欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 教育 > 幼教 > 19914 最小生成树2

19914 最小生成树2

2025/9/23 1:21:48 来源:https://blog.csdn.net/2301_76979886/article/details/146777074  浏览:    关键词:19914 最小生成树2

19914 最小生成树2

⭐️难度:中等
🌟考点:最小生成树
📖
在这里插入图片描述

📚

import java.util.*;public class Main {static class Edge{int u,v,w;Edge(int u,int v,int w){this.u = u;this.v = v;this.w = w;}}static ArrayList<Edge> g = new ArrayList<>(); // 存边static int n;static int m;static class UnionSet{  // 并查集int[] f,sz;UnionSet(int n){f = new int[n+1];sz = new int[n+1];for (int i = 1; i <= n; i++) {f[i] = i;sz[i] = i;}}int find(int x){return f[x] == x ? x : (f[x] = find(f[x]));}void union(int x,int y){int fx = find(x);int fy = find(y);if(sz[fx] < sz[fy]){f[fx] = fy;sz[fy] += sz[fx];}else{f[fy] = fx;sz[fx] += sz[fy];}}}static boolean kruskal(){g.sort(Comparator.comparingInt(e ->e.w));UnionSet us = new UnionSet((n));int cnt = 0;int ans = 0; // 边权for(Edge e : g){if(us.find(e.u) == us.find(e.v)) continue;us.union(e.u,e.v);ans += e.w;if(++cnt == n-1){System.out.println(ans);return true;}}return false;}public static void main(String[] args) {Scanner sc = new Scanner(System.in);n = sc.nextInt();m = sc.nextInt();for (int i = 0; i < m; i++) {g.add(new Edge(sc.nextInt(), sc.nextInt(),sc.nextInt()));}if(!kruskal()){System.out.println("impossible");}}
}

🍎笔记
在这里插入图片描述
在这里插入图片描述

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词