From f487729a83fe68246f49d214efbf5d15b270ccbb Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Wed, 27 Nov 2024 22:13:03 +0100 Subject: [PATCH] =?UTF-8?q?kt:=20add=20=C2=AB3243.=20Shortest=20Distance?= =?UTF-8?q?=20After=20Road=20Addition=20Queries=20I=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit URL: https://leetcode.com/problems/shortest-distance-after-road-addition-queries-i/ Signed-off-by: Matej Focko --- ...-distance-after-road-addition-queries-i.kt | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 kt/shortest-distance-after-road-addition-queries-i.kt diff --git a/kt/shortest-distance-after-road-addition-queries-i.kt b/kt/shortest-distance-after-road-addition-queries-i.kt new file mode 100644 index 0000000..0f260de --- /dev/null +++ b/kt/shortest-distance-after-road-addition-queries-i.kt @@ -0,0 +1,35 @@ +class Solution { + private fun findMinDistance( + n: Int, + graph: List>, + ): Int { + val dp = IntArray(n) + + for (u in (0..n - 2).reversed()) { + dp[u] = graph[u].minOfOrNull { v -> 1 + dp[v] } ?: n + } + + return dp[0] + } + + fun shortestDistanceAfterQueries( + n: Int, + queries: Array, + ): IntArray { + val distances = IntArray(queries.size) + + // Construct initial graph + val graph = (1..n).map { mutableListOf(it) }.toList() + graph.last().removeLast() + + // Process queries + for (query in queries.withIndex()) { + val (u, v) = query.value[0] to query.value[1] + graph[u].add(v) + + distances[query.index] = findMinDistance(n, graph) + } + + return distances + } +}