2026-01-16 21:00:38 +09:00

109 lines
2.7 KiB
Swift

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..<N {
guard let input2 = readLine() else { return -1 }
let jewelInfo = input2.split(separator: " ").compactMap{Int($0)}
jewels.append(Jewel(weight: jewelInfo[0], cost: jewelInfo[1]))
}
jewels.sort{$0.weight < $1.weight}
var bags: [Int] = []
for _ in 0..<K {
guard let C = Int(readLine() ?? "") else { return -1 }
bags.append(C)
}
bags.sort(by: <)
var pq = PQ(sort: {(a, b) -> 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())