Advertisement
vkazar

Untitled

Nov 27th, 2023
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 1.54 KB | None | 0 0
  1. package sprint6.tasks.F
  2.  
  3. import java.io.BufferedReader
  4. import java.io.InputStreamReader
  5. import java.util.*
  6.  
  7. typealias Edges = Map<Int, List<Int>>
  8.  
  9. fun main() {
  10.     val buffer = BufferedReader(InputStreamReader(System.`in`))
  11.     val edges = readGraph(buffer, true)
  12.     buffer.readLine().split(" ").map { it.toInt() }
  13.         .let { println(edges.bfs(it[0], it[1])) }
  14.  
  15. }
  16.  
  17. fun readGraph(buffer: BufferedReader, notOriented: Boolean = false): Edges {
  18.     val (vertexCount, edgeCount) = buffer.readLine().split(" ").map { it.toInt() }
  19.     val edgesLocal = List(vertexCount) { it + 1 }.associateWith { mutableListOf<Int>() }
  20.  
  21.     repeat(edgeCount) {
  22.         val (vertex, toVertex) = buffer.readLine().split(" ").map { it.toInt() }
  23.         edgesLocal[vertex]!!.add(toVertex)
  24.         if (notOriented)
  25.             edgesLocal[toVertex]!!.add(vertex)
  26.     }
  27.  
  28.     return edgesLocal
  29. }
  30.  
  31. enum class Color {
  32.     WHITE,
  33.     GREY,
  34.     BLACK
  35. }
  36.  
  37. fun Edges.bfs(v: Int, u: Int): String {
  38.     val colors = Array(size + 1) { Color.WHITE }
  39.     val distance = IntArray(size + 1) { -1 }
  40.     val queue = LinkedList<Int>()
  41.     queue.push(v)
  42.     distance[v] = 0
  43.     colors[v] = Color.GREY
  44.     while (queue.any() && distance[u] < 0) {
  45.         val cur = queue.poll()
  46.         this[cur]!!.forEach {
  47.             if (colors[it] == Color.WHITE) {
  48.                 distance[it] = distance[cur] + 1
  49.                 queue.add(it)
  50.                 colors[it] = Color.GREY
  51.             }
  52.         }
  53.         colors[cur] = Color.BLACK
  54.     }
  55.     return distance[u].toString()
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement