This repository has been archived by the owner on Sep 13, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mst.java
68 lines (52 loc) · 1.47 KB
/
mst.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import java.util.*;
public class mst {
static int[] parent;
public static void main(String[] args) {
int numVerts = 0; // read these from stdin
int numEdges = 0;
Edge[] edges = new Edge[numEdges];
// Put everything it its own set
parent = new int[numVerts];
for (int i = 0; i < parent.length; i++)
parent[i] = i;
// Read in edges...
Arrays.sort(edges, (a, b) -> a.cost - b.cost);
int costTotal = 0;
for (Edge e : edges) {
if (find(e.x) == find(e.y))
continue;
union(e.x, e.y);
costTotal += e.cost;
}
}
private static int find(int a) {
if (parent[a] != a)
parent[a] = find(parent[a]);
return parent[a];
}
private static void union(int a, int b) {
int aRoot = find(a);
int bRoot = find(b);
parent[aRoot] = parent[bRoot];
}
public static boolean completeSpanningTree() {
boolean foundOrphan = false;
for (int i = 0; i < parent.length; i++) {
if (i == parent[i]) {
if (foundOrphan)
return false;
foundOrphan = true;
}
}
return true;
}
private static class Edge {
int x, y;
int cost;
public Edge(int x, int y, int cost) {
this.x = x;
this.y = y;
this.cost = cost;
}
}
}