-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1715_카드 정렬하기.swift
75 lines (59 loc) · 1.71 KB
/
1715_카드 정렬하기.swift
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
69
70
71
72
73
74
75
import Foundation
let n: Int = Int(readLine()!)!
var minHeap: Heap<Int> = Heap<Int>(sort: <)
for _ in 0..<n {
let num: Int = Int(readLine()!)!
minHeap.insert(num)
}
var answer: Int = 0
while minHeap.nodes.count > 1 {
let min1: Int = minHeap.pop()
let min2: Int = minHeap.pop()
answer += min1 + min2
minHeap.insert(min1 + min2)
}
print(answer)
struct Heap<T: Comparable> {
var nodes: [T] = []
let sort: (T, T) -> Bool
var isEmpty: Bool {
return nodes.isEmpty
}
init(sort: @escaping (T, T) -> Bool) {
self.sort = sort
}
mutating func insert(_ element: T) {
var idx = nodes.count
nodes.append(element)
while idx > 0 && sort(nodes[idx], nodes[(idx-1)/2]) {
nodes.swapAt((idx-1)/2, idx)
idx = (idx-1)/2
}
}
mutating func pop() -> T {
nodes.swapAt(0, nodes.count-1)
let popped = nodes.removeLast()
var idx = 0
while idx * 2 + 1 <= nodes.count - 1 {
let lChildIdx: Int = idx * 2 + 1
let rChildIdx: Int = idx * 2 + 2
if rChildIdx < nodes.count {
let childIdx = sort(nodes[lChildIdx], nodes[rChildIdx]) ? lChildIdx : rChildIdx
if sort(nodes[childIdx], nodes[idx]) {
nodes.swapAt(childIdx, idx)
idx = childIdx
} else {
break
}
} else {
if sort(nodes[lChildIdx], nodes[idx]) {
nodes.swapAt(lChildIdx, idx)
idx = lChildIdx
} else {
break
}
}
}
return popped
}
}