859. Kruskal算法求最小生成树(模板)
2024-10-08 10:26:01
给定一个n个点m条边的无向图,图中可能存在重边和自环,边权可能为负数。
求最小生成树的树边权重之和,如果最小生成树不存在则输出impossible。
给定一张边带权的无向图G=(V, E),其中V表示图中点的集合,E表示图中边的集合,n=|V|,m=|E|。
由V中的全部n个顶点和E中n-1条边构成的无向连通子图被称为G的一棵生成树,其中边的权值之和最小的生成树被称为无向图G的最小生成树。
输入格式
第一行包含两个整数n和m。
接下来m行,每行包含三个整数u,v,w,表示点u和点v之间存在一条权值为w的边。
输出格式
共一行,若存在最小生成树,则输出一个整数,表示最小生成树的树边权重之和,如果最小生成树不存在则输出impossible。
数据范围
1≤n≤1051≤n≤105,
1≤m≤2∗1051≤m≤2∗105,
图中涉及边的边权的绝对值均不超过1000。
输入样例:
4 5
1 2 1
1 3 2
1 4 3
2 3 2
3 4 4
输出样例:
6
代码:
//思路:先把所有边按照权值从小到大排序
//枚举每条边a,b和权重w,
//如果a,b不连通,则将这条边加入到集合中 import java.util.Arrays;
import java.util.Scanner; class Node implements Comparable<Node>{
int a;
int b;
int w;
public Node(int a,int b,int w){
this.a=a;
this.b=b;
this.w=w;
}
@Override
public int compareTo(Node o) {
return this.w-o.w;
}
}
public class Main{
static final int N=100005;
static int p[]=new int[N];
static Node node[]=new Node[2*N];
static int n,m;
static int find(int x){
if(p[x]!=x) p[x]=find(p[x]);
return p[x];
}
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
n=scan.nextInt();
m=scan.nextInt();
for(int i=0;i<m;i++){
int a=scan.nextInt();
int b=scan.nextInt();
int w=scan.nextInt();
node[i]=new Node(a,b,w);
}
Arrays.sort(node,0,m);
for(int i=1;i<=n;i++) p[i]=i;
int res=0,cnt=0;
for(int i=0;i<m;i++){
int a=node[i].a;
int b=node[i].b;
if(find(a)!=find(b)){
res+=node[i].w;
cnt++;
p[find(a)]=b;
}
}
//n个点由n-1条边连着
if(cnt!=n-1) System.out.println("impossible");
else System.out.println(res);
}
}
最新文章
- 跨域的get和post的区别
- 实时消息平台NSQ的特性
- 求height数组
- 洛谷P1726 上白泽慧音
- ExtractTablesFromSQL
- yum源的更新问题
- malloc,vmalloc与kmalloc,kfree与vfree的区别和联系
- 自学Xpath的几个例子
- js、html中的单引号、双引号及其转义使用
- hdu1010 Tempter of the Bone---DFS+奇偶剪枝
- Pattern recognition and machine learning 疑难处汇总
- 洛谷P2055假期的宿舍
- Element-UI使用指南
- Unity Blog 学习
- Nowcoder 练习赛26E 树上路径 - 树剖
- Flask如何给多个视图函数增加装饰器
- Linux系统——JumpServer跳板机的搭建和部署
- 【WP8.1】系统控件的bug及修复方案
- 【BZOJ1096】[ZJOI2007]仓库建设 斜率优化
- window 更新 nodejs
热门文章
- HttpMessageNotReadableException
- hexo博客
- RabbitMQ工作模式
- 转载【React Native代码】手写验证码倒计时组件
- 阿里Java架构师分享自己的成长经历,教你如何快速成长为架构师
- nodejs对字符串进行base64转换和解析
- Python中的用open打开文件错误,FileNotFoundError: [Errno 2] No such file or directory:
- numpy 消除Futurewarning
- 前向传播和反向传播实战(Tensor)
- LOJ #2876. 「JOISC 2014 Day2」水壶 BFS+最小生成树+倍增LCA