您的位置:首页 > 理论基础 > 数据结构算法

并查集实现最小生成树的kruskal算法

2017-08-21 21:29 573 查看
import java.util.Arrays;

import java.util.Scanner;

public class 最小生成树kruskal {

private static Edge[] map;
private static int[] father;
private static int ans = 0; //权值的和

static class Edge implements Comparable<Edge>{
int x;
int y;
int cost;
public Edge(int x, int y, int cost) {
super();
this.x = x;
this.y = y;
this.cost = cost;
}
@Override
public int compareTo(Edge e) {
// TODO Auto-generated method stub
return this.cost-e.cost;
}

}
public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
while(sc.hasNext()){
int n= sc.nextInt();
int m = sc.nextInt();
map = new Edge[m];
father = new int[m+1];
for(int i = 0;i<m ;i++){
int x = sc.nextInt();
int y = sc.nextInt();
int cost = sc.nextInt();
map[i] = new Edge(x,y,cost);
}

Kruskal(map,n,m);

System.out.println("权值和:"+ans);
}
}
private static void Kruskal(Edge[] map,int n,int m) {

//并查集的初始化
for(int i = 1;i<=m;i++)
father[i] = i;

Arrays.sort(map);
//合并
for(int i=0;i<m;i++){
int x_root = find(map[i].x);
int y_root = find(map[i].y);
if(x_root != y_root){
ans  += map[i].cost;
//System.out.println("<"+map[i].x+","+map[i].y+">:"+map[i].cost);
father[x_root] = y_root;
}
}

}
private static int find(int x) {
while(father[x]!=x)
x = father[x];
return x;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息