import java.util.Collection;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.PriorityQueue;
import java.util.Set;
import javax.lang.model.type.UnionType;
import java.util.ArrayList;
public class Kruskal {
public class Node {
public int value;
public int in, out;
public ArrayList<Node> nexts;
public ArrayList<Edge> edges;
Node(int value) {
this.value = value;
in = out = 0;
nexts = new ArrayList<Node>();
edges = new ArrayList<Edge>();
}
}
public class Edge {
public int weight;
public Node from, to;
Edge(int weight, Node from, Node to) {
this.weight = weight;
this.from = from;
this.to = to;
}
}
public class Graph {
public HashMap<Integer, Node> nodes;
public HashSet<Edge> edges;
Graph() {
nodes = new HashMap<Integer, Node>();
edges = new HashSet<Edge>();
}
}
public class UnionFind {
private HashMap<Node, Node> fathermap;
private HashMap<Node, Integer> rankmap;
UnionFind() {
fathermap = new HashMap<Node, Node>();
rankmap = new HashMap<Node, Integer>();
}
private Node findFather(Node n) { //找头节点
Node father = fathermap.get(n);
if (father != n) {
father = findFather(father);
}
fathermap.put(n, father);
return father;
}
public void makeSets(Collection<Node> nodes) { //初始化并查集
fathermap.clear();
rankmap.clear();
for (Node node : nodes) {
fathermap.put(node, node);
rankmap.put(node, 1);
}
}
public boolean isSameSet(Node a, Node b) {
return findFather(a) == findFather(b);
}
public void union(Node a, Node b) {
if (a == null || b == null)
return;
Node aF = findFather(a);
Node bF = findFather(b);
if (aF != bF) {
int aFrank = rankmap.get(aF);
int bFrank = rankmap.get(bF);
if (aFrank <= bFrank) {
fathermap.put(aF, bF);
rankmap.put(bF, aFrank + bFrank);
} else {
fathermap.put(bF, aF);
rankmap.put(aF, aFrank + bFrank);
}
}
}
}
public static class EdgeCompartor implements Comparator<Edge> {
public int compare(Edge a, Edge b) { //升序排列
return a.weight - b.weight;
}
}
public static Set<Edge> kruskalMST(Graph graph) {
UnionFind unionFind = new UnionFind();
unionFind.makeSets(graph.nodes.values());
PriorityQueue<Edge> priorityQueue =
new PriorityQueue<>(new EdgeCompartor());
for (Edge edge : graph.edges) {
priorityQueue.add(edge);
}
Set<Edge> result = new HashSet<>();
while (!priorityQueue.isEmpty()) {
Edge edge = priorityQueue.poll();
if (!unionFind.isSameSet(edge.from, edge.to)) {
result.add(edge);
unionFind.union(edge.from, edge.to);
}
}
return result;
}
}
克鲁斯卡尔算法
最新推荐文章于 2022-02-28 14:53:46 发布