Skip to content

Commit

Permalink
2024-03-18 solved
Browse files Browse the repository at this point in the history
  • Loading branch information
SeongHoonC committed Mar 18, 2024
1 parent 9333369 commit 1c1ccfc
Showing 1 changed file with 59 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import java.io.BufferedReader
import java.io.InputStreamReader
import java.util.*
import kotlin.math.min

private const val INF = 987_654_321L
fun main() {
val br = BufferedReader(InputStreamReader(System.`in`))

val (N, E) = br.readLine().split(" ").map { it.toInt() }
val graph = Array(N + 1) { mutableListOf<Pair<Int, Long>>() }
for (i in 0 until E) {
val (start, end, cost) = br.readLine().split(" ").map { it.toInt() }
graph[start].add((end to cost.toLong()))
graph[end].add((start to cost.toLong()))
}

val (v1, v2) = br.readLine().split(" ").map { it.toInt() }
// 1 to v1 + v1 to v2 + v2 to N
val cost1 = dijkstra(N, 1, v1, graph) + dijkstra(N, v1, v2, graph) + dijkstra(N, v2, N, graph)
// 1 to v2 + v2 to v1 + v1 to N
val cost2 = dijkstra(N, 1, v2, graph) + dijkstra(N, v2, v1, graph) + dijkstra(N, v1, N, graph)

val answer = min(cost1, cost2)
println(if (answer >= INF) -1 else answer)
}

// start to end ์ตœ๋‹จ๊ฑฐ๋ฆฌ ๊ตฌํ•˜๊ธฐ
private fun dijkstra(N: Int, start: Int, end: Int, graph: Array<MutableList<Pair<Int, Long>>>): Long {
if (start == end) {
return 0
}
val pq = PriorityQueue<Edge>()
val distance = Array(N + 1) { INF }

distance[start] = 0
pq.add(Edge(start, 0))

while (pq.isNotEmpty()) {
val (now, dist) = pq.poll()
for ((next, cost) in graph[now]) {
val nextCost: Long = dist + cost
if (distance[next] > nextCost) {
distance[next] = nextCost
pq.add(Edge(next, nextCost))
}
}
}

return distance[end]
}

data class Edge(val start: Int, val cost: Long) : Comparable<Edge> {

// ๊ฑฐ๋ฆฌ(๋น„์šฉ)๊ฐ€ ์งง์€ ๊ฒƒ์ด ๋†’์€ ์šฐ์„ ์ˆœ์œ„๋ฅผ ๊ฐ€์ง€๋„๋ก ์„ค์ •
override operator fun compareTo(other: Edge): Int {
return if (this.cost < other.cost) -1 else 1
}
}

0 comments on commit 1c1ccfc

Please sign in to comment.