Skip to content

Instantly share code, notes, and snippets.

@omo
Created August 9, 2022 12:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save omo/8fbf9fdbb4157040a444799e1606c775 to your computer and use it in GitHub Desktop.
Save omo/8fbf9fdbb4157040a444799e1606c775 to your computer and use it in GitHub Desktop.
typealias Node = Int
typealias Edge = Int
typealias Color = Int
fun debugln(str: String) {
// println(str)
assert(!str.isEmpty())
}
fun main() {
val nm = readLine()!!.split(" ").map{ it.toInt() }
val vars = (0 until nm[0]).map { readLine()!!.toInt() }
val edges = (0 until nm[1]).map { readLine()!!.split(" ").map { it.toInt() } }
debugln("vars = $vars edges = $edges")
// Map<Node -> List of Nodes>
val graph = mutableMapOf<Node, MutableList<Node>>()
edges.forEach {
graph.getOrPut(it[0], { mutableListOf<Node>() }).add(it[1])
graph.getOrPut(it[1], { mutableListOf<Node>() }).add(it[0])
}
debugln("g = $graph")
val uncoloredNodes : MutableSet<Node> = (0 until vars.size).map { it }.toMutableSet()
val nodeColors = mutableMapOf<Node, Color>()
val coloring = mutableMapOf<Color, MutableList<Node>>()
fun traverse(n: Node, c: Color) {
if (!uncoloredNodes.contains(n)) {
return
}
uncoloredNodes.remove(n)
nodeColors[n] = c
coloring.getOrPut(c, { mutableListOf<Node>() }).add(n)
graph[n]!!.forEach { traverse(it, c) }
}
while (!uncoloredNodes.isEmpty()) {
val start = uncoloredNodes.elementAt(0)
val color = coloring.size
traverse(start, color)
}
debugln("coloring = $coloring")
if (coloring.values.any { it.map { vars[it] }.sum() != 0 }) {
println("IMPOSSIBLE")
} else {
println("POSSIBLE")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment