[백준] 최단경로 - 골드 4 (Kotlin)

김민형·2022년 6월 17일
0

백준 알고리즘

목록 보기
1/13

문제

방향그래프가 주어지면 주어진 시작점에서 다른 모든 정점으로의 최단 경로를 구하는 프로그램을 작성하시오. 단, 모든 간선의 가중치는 10 이하의 자연수이다.

입력

첫째 줄에 정점의 개수 V와 간선의 개수 E가 주어진다. (1 ≤ V ≤ 20,000, 1 ≤ E ≤ 300,000) 모든 정점에는 1부터 V까지 번호가 매겨져 있다고 가정한다. 둘째 줄에는 시작 정점의 번호 K(1 ≤ K ≤ V)가 주어진다. 셋째 줄부터 E개의 줄에 걸쳐 각 간선을 나타내는 세 개의 정수 (u, v, w)가 순서대로 주어진다. 이는 u에서 v로 가는 가중치 w인 간선이 존재한다는 뜻이다. u와 v는 서로 다르며 w는 10 이하의 자연수이다. 서로 다른 두 정점 사이에 여러 개의 간선이 존재할 수도 있음에 유의한다.

출력

첫째 줄부터 V개의 줄에 걸쳐, i번째 줄에 i번 정점으로의 최단 경로의 경로값을 출력한다. 시작점 자신은 0으로 출력하고, 경로가 존재하지 않는 경우에는 INF를 출력하면 된다.

풀이

단순한 다익스트라 알고리즘 구현 문제

소스 코드

import java.util.PriorityQueue
const val INF = 987654321
fun main(args: Array<String>) {
   /*
5 6
1
5 1 1
1 2 2
1 3 3
2 3 4
2 4 5
3 4 6
    */
    val (V, E) = readLine()!!.split(' ').map { it.toInt() }
    val start = readLine()!!.toInt()
    val graph = Array<ArrayList<Node>>(V+1) { arrayListOf() }

    for (i in 0 until E) {
        val input = readLine()!!.split(' ').map { it.toInt() }
        graph[input[0]].add(Node(input[1], input[2]))
    }
    val result = dijkstra(start, V, graph)

    for (i in 1 until result.size) {
        println(if (result[i] == INF) "INF" else result[i])
    }
}

fun dijkstra(start: Int, V: Int, graph: Array<ArrayList<Node>>): IntArray {
    val queue = PriorityQueue<Node>()
    val dist = IntArray(V+1) {INF}
    val visit = BooleanArray(V+1) {false}

    dist[start] = 0
    queue.offer(Node(start, 0))

    while (queue.isNotEmpty()) {
        val now = queue.poll()

        if (visit[now.end]) continue
        visit[now.end] = true

        for (next in graph[now.end]) {
            if (dist[next.end] > dist[now.end] + next.weight) {
                dist[next.end] = dist[now.end] + next.weight
                queue.offer(Node(next.end, dist[next.end]))
            }
        }
    }

    return dist
}

data class Node(val end: Int, val weight: Int) : Comparable<Node> {
    override fun compareTo(other: Node): Int {
        return weight - other.weight
    }
}
profile
Stick To Nothing!

0개의 댓글