Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package sprint6.tasks.M
- import sprint6.tasks.M.Side.LEFT
- import sprint6.tasks.M.Side.RIGHT
- import java.io.BufferedReader
- import java.io.InputStreamReader
- val left = mutableSetOf<Int>()
- val right = mutableSetOf<Int>()
- lateinit var vertexes: Map<Int, MutableSet<Int>>
- fun main() {
- val buffer = BufferedReader(InputStreamReader(System.`in`))
- val (vertexCount, edgeCount) = buffer.readLine().split(" ").map { it.toInt() }
- vertexes = List(vertexCount) { it + 1 }.associateWith { mutableSetOf() }
- repeat(edgeCount) {
- val (vertex, toVertex) = buffer.readLine().split(" ").map { it.toInt() }
- vertexes[vertex]!!.add(toVertex)
- vertexes[toVertex]!!.add(vertex)
- }
- if (isBipartite()) println("YES")
- else println("NO")
- }
- fun isBipartite() = vertexes.all {
- if (it.value.any())
- isBipartite(it.key, null)
- else
- true
- }
- fun isBipartite(vertex: Int, side: Side?): Boolean {
- val edges = vertexes[vertex] ?: return true
- val (main, other, nextSide) = side.nextIteration(vertex)
- if (vertex in other)
- return false
- main.add(vertex)
- if (edges.filter { it !in other }.any { !isBipartite(it, nextSide) }) return false
- return true
- }
- fun Side?.nextIteration(cur: Int): Triple<MutableSet<Int>, MutableSet<Int>, Side> =
- when (this) {
- LEFT -> Triple(left, right, RIGHT)
- RIGHT -> Triple(right, left, LEFT)
- else -> when (cur) {
- in left -> LEFT.nextIteration(cur)
- in right -> RIGHT.nextIteration(cur)
- else -> LEFT.nextIteration(cur)
- }
- }
- enum class Side {
- LEFT,
- RIGHT
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement