Last active
August 29, 2015 14:03
-
-
Save lala7573/37cf28a00d93c4e3ff77 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
package greeter | |
import scala.collection.mutable | |
import scala.io.Source | |
import java.io.{ File, PrintStream } | |
object hello { | |
def isBipartiteGraph(lines: mutable.ListBuffer[(String, String)], map: mutable.HashMap[String, Boolean]): Boolean = { | |
var remains = mutable.ListBuffer[(String, String)]() | |
lines.map { case (left, right) => | |
if (map.isEmpty) { | |
map += (left -> false) | |
map += (right -> true) | |
} | |
(map.contains(left), map.contains(right)) match { | |
case (true, true) => if (map(left) == map(right)) return false | |
case (true, false) => map += right -> !map(left) | |
case (false, true) => map += left -> !map(right) | |
case (false, false) => remains = (left, right) +: remains | |
} | |
} | |
if (remains.isEmpty) true | |
else { | |
if (remains.equals(lines)) isBipartiteGraph(remains, mutable.HashMap.empty) | |
else isBipartiteGraph(remains, map) | |
} | |
} | |
def process(iter: Iterator[String])(pr: String => Unit) { | |
for (i <- 1 to iter.next().toInt) yield { | |
val seq = List.fill(iter.next().toInt){ | |
val Array(a, b) = iter.next().toString split ' ' | |
(a, b) | |
} | |
pr(s"Case #$i: ${if (isBipartiteGraph(mutable.ListBuffer(seq.toSeq: _*), mutable.HashMap.empty)) "Yes" else "No"}") | |
} | |
} | |
def main(args: Array[String]) { | |
val in = Source.fromFile(new File("A-small-practice-2.in")) | |
val out = new PrintStream(new File("test.out")) | |
try { | |
process(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