20251109 baekjoon
This commit is contained in:
parent
7aae2442d2
commit
c3d11cc909
80
code_study/Baekjoon/swift/1647.swift
Normal file
80
code_study/Baekjoon/swift/1647.swift
Normal file
@ -0,0 +1,80 @@
|
||||
struct Union {
|
||||
var parent: [Int]
|
||||
|
||||
init(_ N: Int) {
|
||||
self.parent = Array(0...N)
|
||||
}
|
||||
|
||||
mutating func findParent(_ x: Int) -> Int {
|
||||
if x != parent[x] {
|
||||
parent[x] = findParent(parent[x])
|
||||
}
|
||||
return parent[x]
|
||||
}
|
||||
|
||||
mutating func union(_ x: Int, _ y: Int) {
|
||||
let parentX = findParent(x)
|
||||
let parentY = findParent(y)
|
||||
|
||||
if parentX < parentY {
|
||||
parent[parentY] = parentX
|
||||
}
|
||||
else {
|
||||
parent[parentX] = parentY
|
||||
}
|
||||
}
|
||||
|
||||
mutating func isSameParent(_ a: Int, _ b: Int) -> Bool {
|
||||
return findParent(a) == findParent(b)
|
||||
}
|
||||
}
|
||||
|
||||
if let input1 = readLine(),
|
||||
let NM = input1.split(separator: " ").compactMap({Int($0)}) as? [Int],
|
||||
let N = NM.first, let M = NM.last
|
||||
{
|
||||
if N==2 {
|
||||
print(0)
|
||||
}
|
||||
else {
|
||||
var edges: [(u:Int, v: Int, w: Int)] = []
|
||||
for _ in 0..<M {
|
||||
guard let input2 = readLine(),
|
||||
let edge = input2.split(separator: " ").compactMap({Int($0)}) as? [Int],
|
||||
edge.count == 3
|
||||
else {continue}
|
||||
|
||||
let u = min(edge[0], edge[1])
|
||||
let v = max(edge[0], edge[1])
|
||||
let w = edge[2]
|
||||
|
||||
edges.append((u: u, v: v, w: w))
|
||||
}
|
||||
|
||||
edges.sort {
|
||||
if $0.w == $1.w {
|
||||
return $0.u < $1.u
|
||||
}
|
||||
return $0.w < $1.w
|
||||
}
|
||||
|
||||
var root = Union(N)
|
||||
var edgeCount = 0
|
||||
var totalWeight = 0
|
||||
|
||||
for e in edges {
|
||||
let (u, v, w) = e
|
||||
|
||||
if !root.isSameParent(u, v) {
|
||||
root.union(u, v)
|
||||
totalWeight += w
|
||||
edgeCount += 1
|
||||
|
||||
if(edgeCount == N-2) {
|
||||
print(totalWeight)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user