Advertisement
vkazar

Untitled

Nov 29th, 2023
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 1.65 KB | None | 0 0
  1. package sprint6.tasks.M
  2.  
  3. import sprint6.tasks.M.Side.LEFT
  4. import sprint6.tasks.M.Side.RIGHT
  5. import java.io.BufferedReader
  6. import java.io.InputStreamReader
  7.  
  8. val left = mutableSetOf<Int>()
  9. val right = mutableSetOf<Int>()
  10.  
  11. lateinit var vertexes: Map<Int, MutableSet<Int>>
  12.  
  13. fun main() {
  14.     val buffer = BufferedReader(InputStreamReader(System.`in`))
  15.     val (vertexCount, edgeCount) = buffer.readLine().split(" ").map { it.toInt() }
  16.     vertexes = List(vertexCount) { it + 1 }.associateWith { mutableSetOf() }
  17.  
  18.     repeat(edgeCount) {
  19.         val (vertex, toVertex) = buffer.readLine().split(" ").map { it.toInt() }
  20.         vertexes[vertex]!!.add(toVertex)
  21.         vertexes[toVertex]!!.add(vertex)
  22.     }
  23.  
  24.     if (isBipartite()) println("YES")
  25.     else println("NO")
  26. }
  27.  
  28. fun isBipartite() = vertexes.all {
  29.     if (it.value.any())
  30.         isBipartite(it.key, null)
  31.     else
  32.         true
  33. }
  34.  
  35. fun isBipartite(vertex: Int, side: Side?): Boolean {
  36.     val edges = vertexes[vertex] ?: return true
  37.     val (main, other, nextSide) = side.nextIteration(vertex)
  38.  
  39.     if (vertex in other)
  40.         return false
  41.     main.add(vertex)
  42.     if (edges.filter { it !in other }.any { !isBipartite(it, nextSide) }) return false
  43.     return true
  44. }
  45.  
  46. fun Side?.nextIteration(cur: Int): Triple<MutableSet<Int>, MutableSet<Int>, Side> =
  47.     when (this) {
  48.         LEFT -> Triple(left, right, RIGHT)
  49.         RIGHT -> Triple(right, left, LEFT)
  50.         else -> when (cur) {
  51.             in left -> LEFT.nextIteration(cur)
  52.             in right -> RIGHT.nextIteration(cur)
  53.             else -> LEFT.nextIteration(cur)
  54.         }
  55.     }
  56.  
  57. enum class Side {
  58.     LEFT,
  59.     RIGHT
  60. }
  61.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement