-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
9333369
commit 1c1ccfc
Showing
1 changed file
with
59 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} | ||
} |