2025-11-30 19:41:06 +09:00

49 lines
1.1 KiB
Swift

if let input1 = readLine(),
let nums1 = input1.split(separator: " ").compactMap({Int($0)}) as? [Int],
let V = nums1.first, let E = nums1.last
{
var edges: [(u: Int, v: Int, w: Int)] = []
for _ in 1...E {
guard let input2 = readLine(),
let nums2 = input2.split(separator: " ").compactMap({Int($0)}) as? [Int],
nums2.count == 3
else { break }
let (u, v, w) = (nums2[0], nums2[1], nums2[2])
edges.append((u: u, v: v, w: w))
}
edges.sort{$0.w < $1.w}
var parents:[Int] = Array(0...V)
func find(_ x: Int) -> Int {
if x != parents[x] {
parents[x] = find(parents[x])
}
return parents[x]
}
func union(_ x: Int, _ y: Int) {
let a = find(x)
let b = find(y)
if a > b {
parents[a] = b
}
else {
parents[b] = a
}
}
var total_weight = 0
for (u, v, w) in edges {
if find(u) != find(v) {
total_weight += w
union(u, v)
}
}
print(total_weight)
}