Last active
August 29, 2015 14:02
-
-
Save sungkmi/dc94fa84cf27b3b5082e 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
object ChargingChaos extends App { | |
def minMove(inputs: Seq[String]): Option[Int] = { | |
def runLength(s: String) = (List.empty[(Char, Int)] /: s) { | |
case ((c, n) :: tail, char) if c == char => | |
(c, n + 1) :: tail | |
case (acc, char) => | |
(char, 1) :: acc | |
}.reverse.unzip | |
val (chars, lengths) = (inputs map runLength).unzip | |
if (chars.toSet.size > 1) None | |
else Some { | |
(List.fill(lengths.head.size)(List.empty[Int]) /: lengths) { | |
_ zip _ map { case (acc, x) => x :: acc } | |
}.map { acc => | |
val diff = acc.toVector.sorted | |
val median = diff(diff.size / 2) | |
diff.map(math abs _ - median).sum | |
}.sum | |
} | |
} | |
def process(iter: Iterator[String])(out: String => Unit) = | |
for (i <- 1 to iter.next().toInt) { | |
val n = iter.next().toInt | |
val input = Seq.fill(n)(iter.next()) | |
out(s"Case #$i: ${minMove(input) getOrElse "Fegla Won"}") | |
} | |
import java.io._ | |
val out = new PrintStream(new File("a.out")) | |
try { | |
process(io.Source.fromFile("A-large-practice.in").getLines) { s: String => | |
out.println(s) | |
} | |
} finally { | |
out.flush; out.close | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment