백준 - 최단경로 (1753)

Seoyoung Lee·2023년 2월 20일
0

알고리즘

목록 보기
52/104
post-thumbnail
import Foundation

public struct Heap<T> {
    
    private var nodes = [T]()
    
    private var orderCriteria: (T, T) -> Bool
    
    public init(sort: @escaping (T, T) -> Bool) {
        self.orderCriteria = sort
    }
    
    public init(array: [T], sort: @escaping (T, T) -> Bool) {
        self.orderCriteria = sort
        configureHeap(from: array)
    }
    
    public var count: Int {
        return nodes.count
    }
    
    public func peek() -> T? {
        return nodes.first
    }
    
    func isEmpty() -> Bool {
        return nodes.isEmpty
    }
    
    public mutating func insert(_ value: T) {
        nodes.append(value)
        shiftUp(nodes.count - 1)
    }
    
    public mutating func remove() -> T? {
        guard !nodes.isEmpty else { return nil }
        
        if nodes.count == 1 {
            return nodes.removeLast()
        } else {
            let value = nodes[0]
            nodes[0] = nodes.removeLast()
            shiftDown(0)
            return value
        }
    }
    
    public mutating func remove(at index: Int) -> T? {
        guard index < nodes.count else { return nil }
        
        let lastIndex = nodes.count-1
        if index != lastIndex {
            nodes.swapAt(index, lastIndex)
            shiftDown(from: index, until: lastIndex)
            shiftUp(index)
        }
        
        return nodes.removeLast()
    }
    
    private mutating func configureHeap(from array: [T]) {
           nodes = array
           
           for i in stride(from: nodes.count/2 - 1, through: 0, by: -1) {
               shiftDown(i)
           }
       }
    
    private func parentIndex(ofIndex i: Int) -> Int {
        return (i - 1) / 2
    }
    
    private func leftChildIndex(ofIndex i: Int) -> Int {
        return 2*i + 1
    }
    
    private func rightChildIndex(ofIndex i: Int) -> Int {
        return 2*i + 2
    }
    
    private mutating func shiftUp(_ index: Int) {
        var childIndex = index
        let child = nodes[childIndex] // 처음에 노드를 저장해두고 인덱스를 구한 후 바꿔준다.
        var parentIndex = self.parentIndex(ofIndex: index)
        
        while childIndex > 0 && orderCriteria(child, nodes[parentIndex]) {
            nodes[childIndex] = nodes[parentIndex]
            childIndex = parentIndex
            parentIndex = self.parentIndex(ofIndex: childIndex)
        }
        
        nodes[childIndex] = child
    }
    
    private mutating func shiftDown(from index: Int, until endIndex: Int) {
        let leftChildIndex = self.leftChildIndex(ofIndex: index)
        let rightChildIndex = leftChildIndex + 1
        
        var first = index
        if leftChildIndex < endIndex && orderCriteria(nodes[leftChildIndex], nodes[first]) {
            first = leftChildIndex
        }
        if rightChildIndex < endIndex && orderCriteria(nodes[rightChildIndex], nodes[first]) {
            first = rightChildIndex
        }
        if first == index { return }
        
        nodes.swapAt(index, first)
        shiftDown(from: first, until: endIndex)
    }
    
    private mutating func shiftDown(_ index: Int) {
        shiftDown(from: index, until: nodes.count)
    }
    
}

struct Node {
    let vertex: Int
    let value: Int
}

let input = readLine()!.split(separator: " ").map{ Int(String($0))! }
let (V, E) = (input[0], input[1])
let start = Int(readLine()!)!

var graph: [[Node]] = Array(repeating: [], count: V+1)
// 인접리스트 만들기
for _ in 0..<E {
    let input = readLine()!.split(separator: " ").map{ Int(String($0))! }
    graph[input[0]].append(Node(vertex: input[1], value: input[2]))
}

// 다익스트라 알고리즘
var visited = Array(repeating: false, count: V+1)
var distance = Array(repeating: Int.max, count: V+1)
var pq = Heap<Node>(sort: { $0.value < $1.value })
distance[start] = 0
pq.insert(Node(vertex: start, value: 0))

while !pq.isEmpty() {
    let now = pq.remove()!
    if visited[now.vertex] { continue }
    visited[now.vertex] = true
    for next in graph[now.vertex] {
        if distance[next.vertex] > distance[now.vertex] + next.value {
            distance[next.vertex] = distance[now.vertex] + next.value
            pq.insert(Node(vertex: next.vertex, value: distance[next.vertex]))
        }
    }
}

for i in 1...V {
    print(distance[i] == Int.max ? "INF" : distance[i])
}
  • 다익스트라 알고리즘을 구현하는 기본적인 문제
  • 시간 복잡도를 개선하기 위해 인접리스트와 우선순위 큐를 사용한다.
profile
나의 내일은 파래 🐳

0개의 댓글