int kruskal(int n, int[][] edges) {
Arrays.sort(edges, Comparator.comparingInt(edge -> edge[2]));
UnionFind uf = new UnionFind(n);
int cost = 0;
for (int[] edge : edges) {
if (uf.union(edge[0], edge[1])) cost += edge[2];
}
return cost;
}
def kruskal(n: int, edges: list[tuple[int, int, int]]) -> int:
uf = UnionFind(n)
cost = 0
for a, b, weight in sorted(edges, key=lambda edge: edge[2]):
if uf.union(a, b):
cost += weight
return cost
def kruskal(n: Int, edges: Array[Array[Int]]): Int =
val uf = new UnionFind(n)
var cost = 0
for edge <- edges.sortBy(_(2)) do
if uf.union(edge(0), edge(1)) then cost += edge(2)
cost
int kruskal(int n, std::vector<Edge>& edges) {
std::sort(edges.begin(), edges.end(), [](const Edge& a, const Edge& b) {
return a.weight < b.weight;
});
UnionFind uf(n);
int cost = 0;
for (const Edge& edge : edges) {
if (uf.unite(edge.a, edge.b)) cost += edge.weight;
}
return cost;
}