Last active
December 18, 2015 13:00
-
-
Save handrake/6dd2cedc9a3e8b1ad10a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.PrintStream | |
import scala.collection.mutable | |
import scala.io.Source | |
object gGrid { | |
val directions = List((1, 0), (0, 1), (-1, 0), (0, -1)) | |
case class Cmd(command:Char, x:Int = 0, y:Int = 0, value:Int = 0) | |
def solve(ones: mutable.Set[(Int, Int)], ops: Seq[Cmd]): Seq[Int] = { | |
val results = mutable.ListBuffer[Int]() | |
for (op <- ops) { | |
op match { | |
case c:Cmd if c.command == 'Q' => | |
var count = 0 | |
val counted = mutable.Set[(Int, Int)]() | |
while (ones.nonEmpty) { | |
val workList = mutable.ListBuffer(ones.head) | |
while (workList.nonEmpty) { | |
val one = workList.remove(0) | |
ones -= one | |
counted += one | |
workList.appendAll( | |
for (p <- directions; t = Tuple2(one._1 + p._1, one._2 + p._2) if ones.contains(t) && !workList.contains(t)) | |
yield t | |
) | |
} | |
count = count + 1 | |
} | |
results.append(count) | |
ones ++= counted | |
case Cmd('M', x, y, v) => | |
if (v == 1) { | |
ones += Tuple2(x, y) | |
} else { | |
ones -= Tuple2(x, y) | |
} | |
} | |
} | |
results | |
} | |
def main(args: Array[String]): Unit = { | |
val INPUT = "A-large-practice.in" | |
// val INPUT = "1.in" | |
val OUTPUT = INPUT.takeWhile(_ != '.') + ".out" | |
val isConsole = false | |
val itr = Source.fromFile(INPUT).getLines() | |
val stream = if (isConsole) Console.out else new PrintStream(OUTPUT) | |
try { | |
val t = itr.next().toInt | |
(1 to t).foreach { x => | |
val Array(r, c) = itr.next().split(" ").map(_.toInt) | |
val ones = (0 until r).flatMap { y => | |
val line = itr.next() | |
line.zipWithIndex.filter(_._1 == '1').map( i => (y, i._2)) | |
} | |
val n = itr.next().toInt | |
val commands = for (x <- (0 until n)) yield { | |
val line = itr.next().split(" ") | |
if (line.length == 1) { | |
Cmd('Q') | |
} else { | |
Cmd('M', line(1).toInt, line(2).toInt, line(3).toInt) | |
} | |
} | |
stream.println(s"Case #$x:") | |
solve(mutable.Set(ones:_*), commands).foreach { r => | |
stream.println(r) | |
} | |
} | |
} finally { | |
stream.flush() | |
if (!isConsole) stream.close() | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment