Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

17-SeongHoonC #62

Merged
merged 1 commit into from
Mar 28, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
}
}
Comment on lines +53 to +59
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

λ”°λ‘œ μš°μ„ μˆœμœ„ 큐 데이터 κ΅¬μ‘°κΉŒμ§€ λ§Œλ“€μ–΄μ„œ ν•΄μ•Όν•˜λŠ”κ±΄κ°€μš” μ½”ν‹€λ¦°μ—μ„œλŠ”????

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

κ·Έλ ‡μŠ΅λ‹ˆλ‹€ ν•˜ν•˜

Loading