diff --git a/code_study/Baekjoon/swift/1202.swift b/code_study/Baekjoon/swift/1202.swift new file mode 100644 index 0000000..bb0e84e --- /dev/null +++ b/code_study/Baekjoon/swift/1202.swift @@ -0,0 +1,108 @@ +struct Jewel { + var weight: Int + var cost: Int +} + +struct PQ { + var nodes: [Jewel] = [] + let sort: (Jewel, Jewel) -> Bool + + init(sort: @escaping (Jewel, Jewel) -> Bool) { + self.sort = sort + } + + var isEmpty: Bool { + return nodes.isEmpty + } + + mutating func insert(_ element: Jewel) { + nodes.append(element) + shiftUp(from: nodes.count - 1) + } + + mutating func pop() -> Jewel? { + if nodes.isEmpty { return nil } + if nodes.count == 1 { return nodes.removeLast() } + + let root = nodes[0] + nodes[0] = nodes.removeLast() + shiftDown(from: 0) + return root + } + + private mutating func shiftUp(from index: Int) { + var child = index + var parent = (child - 1) / 2 + + while child > 0 && sort(nodes[child], nodes[parent]) { + nodes.swapAt(child, parent) + child = parent + parent = (child - 1) / 2 + } + } + + private mutating func shiftDown(from index: Int) { + var parent = index + + while true { + let left = parent * 2 + 1 + let right = parent * 2 + 2 + var candidate = parent + + if left < nodes.count && sort(nodes[left], nodes[candidate]) { + candidate = left + } + if right < nodes.count && sort(nodes[right], nodes[candidate]) { + candidate = right + } + + if candidate == parent { return } + + nodes.swapAt(parent, candidate) + parent = candidate + } + } +} + +func solve() -> Int { + guard let input1 = readLine(), + let NK = input1.split(separator: " ").compactMap({Int($0)}) as? [Int], + let N = NK.first, let K = NK.last + else { return -1 } + + var jewels: [Jewel] = [] + for _ in 0.. Bool in return a.cost > b.cost}) + var idx: Int = 0 + var ans: Int = 0 + + for bag in bags { + while idx < jewels.count && bag >= jewels[idx].weight { + pq.insert(jewels[idx]) + idx += 1 + } + if !pq.isEmpty { + guard let jewel = pq.pop() else { return -1 } + ans += jewel.cost + } + } + + return ans +} + +print(solve()) diff --git a/code_study/Baekjoon/swift/27172.swift b/code_study/Baekjoon/swift/27172.swift new file mode 100644 index 0000000..a0d4986 --- /dev/null +++ b/code_study/Baekjoon/swift/27172.swift @@ -0,0 +1,35 @@ +import Foundation + +func solve() { + guard let _ = Int(readLine() ?? ""), + let input = readLine(), + let nums = input.split(separator: " ").compactMap({Int($0)}) as? [Int], + let MAX_NUM = nums.max() + else { return } + + var score: [Int] = Array(repeating: 0, count: MAX_NUM+1) + var cards: [Bool] = Array(repeating: false, count: MAX_NUM+1) + + for n in nums { + cards[n] = true + } + + for n in nums { + for i in stride(from: 2*n, through: MAX_NUM, by: n) { + if cards[i] { + score[n] += 1 + score[i] -= 1 + } + } + } + + var result: [String] = [] + + for n in nums { + result.append(String(score[n])) + } + + print(result.joined(separator: " ")) +} + +solve()