最小生成树(Kruskal)

题目描述

编程实现Kruskal算法,求图的最小生成树(MST)的权重。

输入

每组数据分为两个部分,第一部分为图的点数n,和边数m,
第二部分为m行,每一行输入三个数字,前两个为两个顶点的编号,第三个为边权重。

输出

最小生成树的权重。

样例输入

3 3
0 1 10
0 2 15
1 2 50

样例输出

25

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;

public class Main {

	static int pa[];
	static int rank[];
	static int num;
	
	static class tree implements Comparable<tree> {
		int x;
		int y;
		int w;
		@Override
		public int compareTo(tree o) {
			// TODO Auto-generated method stub
			return Integer.compare(w, o.w);
		}
		
		tree(int x,int y,int w){
			this.x=x;
			this.y=y;
			this.w=w;
		}
	}
	
	static int find_set(int x) {//路径压缩查找
		if(x!=pa[x]) {
			pa[x]=find_set(pa[x]);
		}
		return pa[x];
	}
	
	static boolean union_set(int x,int y,int w) {
		x=find_set(x);
		y=find_set(y);
		if(x==y) {
			return false;
		}
		if(rank[x]>rank[y]) {
			pa[y]=x;
		} else {
			if(rank[x]==rank[y]) rank[y]++;
			pa[x]=y;
		}
		num+=w;
		return true;
	}
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner sc =new Scanner(System.in);
		int n=sc.nextInt();
		int m=sc.nextInt();
		
		pa=new int[105];
		rank=new int[105];
		for(int i=1;i<=n;i++) {
			pa[i]=i;
			rank[i]=0;
		}
		num=0;
		List<tree>trees=new ArrayList<tree>();
		for(int i=0;i<m;i++) {
			trees.add(new tree(sc.nextInt(), sc.nextInt(), sc.nextInt()));
		}
		Collections.sort(trees);
		for(tree t:trees) {
			int x=t.x;
			int y=t.y;
			int w=t.w;
			union_set(x, y, w);
		}
		System.out.println(num);
	}

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

是君倩

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值