import ;
import ;
import ;
import ;
import ;
import ;
/**
*
* kruskal算法 适用范围:要求无向图
*
*/
//undirected graph only
public class Code_04_Kruskal {
// Union-Find Set
public static class UnionFind {
private HashMap<Node, Node> fatherMap;
private HashMap<Node, Integer> rankMap;
public UnionFind() {
fatherMap = new HashMap<Node, Node>();
rankMap = new HashMap<Node, Integer>();
}
private Node findFather(Node n) {
Node father = (n);
if (father != n) {
father = findFather(father);
}
(n, father);
return father;
}
public void makeSets(Collection<Node> nodes) {
();
();
for (Node node : nodes) {
(node, node);
(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 aFather = findFather(a);
Node bFather = findFather(b);
if (aFather != bFather) {
int aFrank = (aFather);
int bFrank = (bFather);
if (aFrank <= bFrank) {
(aFather, bFather);
(bFather, aFrank + bFrank);
} else {
(bFather, aFather);
(aFather, aFrank + bFrank);
}
}
}
}
public static class EdgeComparator implements Comparator<Edge> {
@Override
public int compare(Edge o1, Edge o2) {
return - ;
}
}
public static Set<Edge> kruskalMST(Graph graph) {
UnionFind unionFind = new UnionFind();//生成一个并查集
(());
//生成一个优先级队列(堆)
PriorityQueue<Edge> priorityQueue = new PriorityQueue<>(new EdgeComparator());
for (Edge edge : ) {
(edge);
}
Set<Edge> result = new HashSet<>();
while (!()) {
Edge edge = ();
if (!(, )) {
(edge);
(, );
}
}
return result;
}
}